es6.js 4.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055
  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. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. var finalVertexCode;
  143. this._loadVertexShaderAsync(vertexSource)
  144. .then(function (vertexCode) {
  145. return _this._processIncludesAsync(vertexCode);
  146. })
  147. .then(function (vertexCodeWithIncludes) {
  148. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  149. return _this._loadFragmentShaderAsync(fragmentSource);
  150. })
  151. .then(function (fragmentCode) {
  152. return _this._processIncludesAsync(fragmentCode);
  153. })
  154. .then(function (fragmentCodeWithIncludes) {
  155. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  156. if (baseName) {
  157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  159. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  160. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  161. }
  162. else {
  163. _this._vertexSourceCode = finalVertexCode;
  164. _this._fragmentSourceCode = migratedFragmentCode;
  165. }
  166. _this._prepareEffect();
  167. });
  168. }
  169. Object.defineProperty(Effect.prototype, "key", {
  170. get: function () {
  171. return this._key;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. // Properties
  177. Effect.prototype.isReady = function () {
  178. return this._isReady;
  179. };
  180. Effect.prototype.getEngine = function () {
  181. return this._engine;
  182. };
  183. Effect.prototype.getProgram = function () {
  184. return this._program;
  185. };
  186. Effect.prototype.getAttributesNames = function () {
  187. return this._attributesNames;
  188. };
  189. Effect.prototype.getAttributeLocation = function (index) {
  190. return this._attributes[index];
  191. };
  192. Effect.prototype.getAttributeLocationByName = function (name) {
  193. var index = this._attributesNames.indexOf(name);
  194. return this._attributes[index];
  195. };
  196. Effect.prototype.getAttributesCount = function () {
  197. return this._attributes.length;
  198. };
  199. Effect.prototype.getUniformIndex = function (uniformName) {
  200. return this._uniformsNames.indexOf(uniformName);
  201. };
  202. Effect.prototype.getUniform = function (uniformName) {
  203. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  204. };
  205. Effect.prototype.getSamplers = function () {
  206. return this._samplers;
  207. };
  208. Effect.prototype.getCompilationError = function () {
  209. return this._compilationError;
  210. };
  211. // Methods
  212. Effect.prototype.executeWhenCompiled = function (func) {
  213. if (this.isReady()) {
  214. func(this);
  215. return;
  216. }
  217. this.onCompileObservable.add(function (effect) {
  218. func(effect);
  219. });
  220. };
  221. /** @ignore */
  222. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  223. if (BABYLON.Tools.IsWindowObjectExist()) {
  224. // DOM element ?
  225. if (vertex instanceof HTMLElement) {
  226. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  227. return Promise.resolve(vertexCode);
  228. }
  229. }
  230. // Base64 encoded ?
  231. if (vertex.substr(0, 7) === "base64:") {
  232. var vertexBinary = window.atob(vertex.substr(7));
  233. return Promise.resolve(vertexBinary);
  234. }
  235. // Is in local store ?
  236. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  237. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  238. }
  239. var vertexShaderUrl;
  240. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  241. vertexShaderUrl = vertex;
  242. }
  243. else {
  244. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  245. }
  246. // Vertex shader
  247. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  248. };
  249. /** @ignore */
  250. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  251. if (BABYLON.Tools.IsWindowObjectExist()) {
  252. // DOM element ?
  253. if (fragment instanceof HTMLElement) {
  254. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  255. return Promise.resolve(fragmentCode);
  256. }
  257. }
  258. // Base64 encoded ?
  259. if (fragment.substr(0, 7) === "base64:") {
  260. var fragmentBinary = window.atob(fragment.substr(7));
  261. return Promise.resolve(fragmentBinary);
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  266. }
  267. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  268. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  269. }
  270. var fragmentShaderUrl;
  271. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  272. fragmentShaderUrl = fragment;
  273. }
  274. else {
  275. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  276. }
  277. // Fragment shader
  278. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  279. };
  280. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  281. // Rebuild shaders source code
  282. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  283. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  284. vertexCode = prefix + vertexCode;
  285. fragmentCode = prefix + fragmentCode;
  286. // Number lines of shaders source code
  287. var i = 2;
  288. var regex = /\n/gm;
  289. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  290. i = 2;
  291. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. // Dump shaders name and formatted source code
  293. if (this.name.vertexElement) {
  294. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  295. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  296. }
  297. else if (this.name.vertex) {
  298. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  299. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  300. }
  301. else {
  302. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  303. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  304. }
  305. };
  306. ;
  307. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  308. var preparedSourceCode = this._processPrecision(sourceCode);
  309. if (this._engine.webGLVersion == 1) {
  310. return preparedSourceCode;
  311. }
  312. // Already converted
  313. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  314. return preparedSourceCode.replace("#version 300 es", "");
  315. }
  316. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  317. // Remove extensions
  318. // #extension GL_OES_standard_derivatives : enable
  319. // #extension GL_EXT_shader_texture_lod : enable
  320. // #extension GL_EXT_frag_depth : enable
  321. // #extension GL_EXT_draw_buffers : require
  322. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  323. var result = preparedSourceCode.replace(regex, "");
  324. // Migrate to GLSL v300
  325. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  326. result = result.replace(/attribute[ \t]/g, "in ");
  327. result = result.replace(/[ \t]attribute/g, " in");
  328. if (isFragment) {
  329. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  330. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  331. result = result.replace(/texture2D\s*\(/g, "texture(");
  332. result = result.replace(/textureCube\s*\(/g, "texture(");
  333. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  334. result = result.replace(/gl_FragColor/g, "glFragColor");
  335. result = result.replace(/gl_FragData/g, "glFragData");
  336. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  337. }
  338. return result;
  339. };
  340. Effect.prototype._processIncludesAsync = function (sourceCode) {
  341. var _this = this;
  342. return new Promise(function (resolve, reject) {
  343. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  344. var match = regex.exec(sourceCode);
  345. var returnValue = sourceCode;
  346. while (match != null) {
  347. var includeFile = match[1];
  348. // Uniform declaration
  349. if (includeFile.indexOf("__decl__") !== -1) {
  350. includeFile = includeFile.replace(/__decl__/, "");
  351. if (_this._engine.supportsUniformBuffers) {
  352. includeFile = includeFile.replace(/Vertex/, "Ubo");
  353. includeFile = includeFile.replace(/Fragment/, "Ubo");
  354. }
  355. includeFile = includeFile + "Declaration";
  356. }
  357. if (Effect.IncludesShadersStore[includeFile]) {
  358. // Substitution
  359. var includeContent = Effect.IncludesShadersStore[includeFile];
  360. if (match[2]) {
  361. var splits = match[3].split(",");
  362. for (var index = 0; index < splits.length; index += 2) {
  363. var source = new RegExp(splits[index], "g");
  364. var dest = splits[index + 1];
  365. includeContent = includeContent.replace(source, dest);
  366. }
  367. }
  368. if (match[4]) {
  369. var indexString = match[5];
  370. if (indexString.indexOf("..") !== -1) {
  371. var indexSplits = indexString.split("..");
  372. var minIndex = parseInt(indexSplits[0]);
  373. var maxIndex = parseInt(indexSplits[1]);
  374. var sourceIncludeContent = includeContent.slice(0);
  375. includeContent = "";
  376. if (isNaN(maxIndex)) {
  377. maxIndex = _this._indexParameters[indexSplits[1]];
  378. }
  379. for (var i = minIndex; i < maxIndex; i++) {
  380. if (!_this._engine.supportsUniformBuffers) {
  381. // Ubo replacement
  382. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  383. return p1 + "{X}";
  384. });
  385. }
  386. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  387. }
  388. }
  389. else {
  390. if (!_this._engine.supportsUniformBuffers) {
  391. // Ubo replacement
  392. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  393. return p1 + "{X}";
  394. });
  395. }
  396. includeContent = includeContent.replace(/\{X\}/g, indexString);
  397. }
  398. }
  399. // Replace
  400. returnValue = returnValue.replace(match[0], includeContent);
  401. }
  402. else {
  403. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  404. _this._engine._loadFileAsync(includeShaderUrl)
  405. .then(function (fileContent) {
  406. Effect.IncludesShadersStore[includeFile] = fileContent;
  407. return _this._processIncludesAsync(returnValue);
  408. })
  409. .then(function (returnValue) {
  410. resolve(returnValue);
  411. });
  412. return;
  413. }
  414. match = regex.exec(sourceCode);
  415. }
  416. resolve(returnValue);
  417. });
  418. };
  419. Effect.prototype._processPrecision = function (source) {
  420. if (source.indexOf("precision highp float") === -1) {
  421. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  422. source = "precision mediump float;\n" + source;
  423. }
  424. else {
  425. source = "precision highp float;\n" + source;
  426. }
  427. }
  428. else {
  429. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  430. source = source.replace("precision highp float", "precision mediump float");
  431. }
  432. }
  433. return source;
  434. };
  435. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  436. var _this = this;
  437. this._isReady = false;
  438. this._vertexSourceCodeOverride = vertexSourceCode;
  439. this._fragmentSourceCodeOverride = fragmentSourceCode;
  440. this.onError = function (effect, error) {
  441. if (onError) {
  442. onError(error);
  443. }
  444. };
  445. this.onCompiled = function () {
  446. var scenes = _this.getEngine().scenes;
  447. for (var i = 0; i < scenes.length; i++) {
  448. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  449. }
  450. if (onCompiled) {
  451. onCompiled(_this._program);
  452. }
  453. };
  454. this._fallbacks = null;
  455. this._prepareEffect();
  456. };
  457. Effect.prototype.getSpecificUniformLocations = function (names) {
  458. var engine = this._engine;
  459. return engine.getUniforms(this._program, names);
  460. };
  461. Effect.prototype._prepareEffect = function () {
  462. var attributesNames = this._attributesNames;
  463. var defines = this.defines;
  464. var fallbacks = this._fallbacks;
  465. this._valueCache = {};
  466. var previousProgram = this._program;
  467. try {
  468. var engine = this._engine;
  469. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  470. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  471. }
  472. else {
  473. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  474. }
  475. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  476. if (engine.supportsUniformBuffers) {
  477. for (var name in this._uniformBuffersNames) {
  478. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  479. }
  480. }
  481. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  482. this._attributes = engine.getAttributes(this._program, attributesNames);
  483. var index;
  484. for (index = 0; index < this._samplers.length; index++) {
  485. var sampler = this.getUniform(this._samplers[index]);
  486. if (sampler == null) {
  487. this._samplers.splice(index, 1);
  488. index--;
  489. }
  490. }
  491. engine.bindSamplers(this);
  492. this._compilationError = "";
  493. this._isReady = true;
  494. if (this.onCompiled) {
  495. this.onCompiled(this);
  496. }
  497. this.onCompileObservable.notifyObservers(this);
  498. this.onCompileObservable.clear();
  499. // Unbind mesh reference in fallbacks
  500. if (this._fallbacks) {
  501. this._fallbacks.unBindMesh();
  502. }
  503. if (previousProgram) {
  504. this.getEngine()._deleteProgram(previousProgram);
  505. }
  506. }
  507. catch (e) {
  508. this._compilationError = e.message;
  509. // Let's go through fallbacks then
  510. BABYLON.Tools.Error("Unable to compile effect:");
  511. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  512. return " " + uniform;
  513. }));
  514. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  515. return " " + attribute;
  516. }));
  517. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  518. BABYLON.Tools.Error("Error: " + this._compilationError);
  519. if (previousProgram) {
  520. this._program = previousProgram;
  521. this._isReady = true;
  522. if (this.onError) {
  523. this.onError(this, this._compilationError);
  524. }
  525. this.onErrorObservable.notifyObservers(this);
  526. }
  527. if (fallbacks && fallbacks.isMoreFallbacks) {
  528. BABYLON.Tools.Error("Trying next fallback.");
  529. this.defines = fallbacks.reduce(this.defines);
  530. this._prepareEffect();
  531. }
  532. else {
  533. if (this.onError) {
  534. this.onError(this, this._compilationError);
  535. }
  536. this.onErrorObservable.notifyObservers(this);
  537. this.onErrorObservable.clear();
  538. // Unbind mesh reference in fallbacks
  539. if (this._fallbacks) {
  540. this._fallbacks.unBindMesh();
  541. }
  542. }
  543. }
  544. };
  545. Object.defineProperty(Effect.prototype, "isSupported", {
  546. get: function () {
  547. return this._compilationError === "";
  548. },
  549. enumerable: true,
  550. configurable: true
  551. });
  552. Effect.prototype._bindTexture = function (channel, texture) {
  553. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  554. };
  555. Effect.prototype.setTexture = function (channel, texture) {
  556. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  557. };
  558. Effect.prototype.setTextureArray = function (channel, textures) {
  559. if (this._samplers.indexOf(channel + "Ex") === -1) {
  560. var initialPos = this._samplers.indexOf(channel);
  561. for (var index = 1; index < textures.length; index++) {
  562. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  563. }
  564. }
  565. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  566. };
  567. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  568. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  569. };
  570. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  571. var cache = this._valueCache[uniformName];
  572. var flag = matrix.updateFlag;
  573. if (cache !== undefined && cache === flag) {
  574. return false;
  575. }
  576. this._valueCache[uniformName] = flag;
  577. return true;
  578. };
  579. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  580. var cache = this._valueCache[uniformName];
  581. if (!cache) {
  582. cache = [x, y];
  583. this._valueCache[uniformName] = cache;
  584. return true;
  585. }
  586. var changed = false;
  587. if (cache[0] !== x) {
  588. cache[0] = x;
  589. changed = true;
  590. }
  591. if (cache[1] !== y) {
  592. cache[1] = y;
  593. changed = true;
  594. }
  595. return changed;
  596. };
  597. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  598. var cache = this._valueCache[uniformName];
  599. if (!cache) {
  600. cache = [x, y, z];
  601. this._valueCache[uniformName] = cache;
  602. return true;
  603. }
  604. var changed = false;
  605. if (cache[0] !== x) {
  606. cache[0] = x;
  607. changed = true;
  608. }
  609. if (cache[1] !== y) {
  610. cache[1] = y;
  611. changed = true;
  612. }
  613. if (cache[2] !== z) {
  614. cache[2] = z;
  615. changed = true;
  616. }
  617. return changed;
  618. };
  619. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  620. var cache = this._valueCache[uniformName];
  621. if (!cache) {
  622. cache = [x, y, z, w];
  623. this._valueCache[uniformName] = cache;
  624. return true;
  625. }
  626. var changed = false;
  627. if (cache[0] !== x) {
  628. cache[0] = x;
  629. changed = true;
  630. }
  631. if (cache[1] !== y) {
  632. cache[1] = y;
  633. changed = true;
  634. }
  635. if (cache[2] !== z) {
  636. cache[2] = z;
  637. changed = true;
  638. }
  639. if (cache[3] !== w) {
  640. cache[3] = w;
  641. changed = true;
  642. }
  643. return changed;
  644. };
  645. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  646. var bufferName = this._uniformBuffersNames[name];
  647. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  648. return;
  649. }
  650. Effect._baseCache[bufferName] = buffer;
  651. this._engine.bindUniformBufferBase(buffer, bufferName);
  652. };
  653. Effect.prototype.bindUniformBlock = function (blockName, index) {
  654. this._engine.bindUniformBlock(this._program, blockName, index);
  655. };
  656. Effect.prototype.setInt = function (uniformName, value) {
  657. var cache = this._valueCache[uniformName];
  658. if (cache !== undefined && cache === value)
  659. return this;
  660. this._valueCache[uniformName] = value;
  661. this._engine.setInt(this.getUniform(uniformName), value);
  662. return this;
  663. };
  664. Effect.prototype.setIntArray = function (uniformName, array) {
  665. this._valueCache[uniformName] = null;
  666. this._engine.setIntArray(this.getUniform(uniformName), array);
  667. return this;
  668. };
  669. Effect.prototype.setIntArray2 = function (uniformName, array) {
  670. this._valueCache[uniformName] = null;
  671. this._engine.setIntArray2(this.getUniform(uniformName), array);
  672. return this;
  673. };
  674. Effect.prototype.setIntArray3 = function (uniformName, array) {
  675. this._valueCache[uniformName] = null;
  676. this._engine.setIntArray3(this.getUniform(uniformName), array);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray4 = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray4(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setFloatArray = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setFloatArray(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setArray = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setArray(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setArray2 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setArray2(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setArray3 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setArray3(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray4 = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray4(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setMatrices = function (uniformName, matrices) {
  725. if (!matrices) {
  726. return this;
  727. }
  728. this._valueCache[uniformName] = null;
  729. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  730. return this;
  731. };
  732. Effect.prototype.setMatrix = function (uniformName, matrix) {
  733. if (this._cacheMatrix(uniformName, matrix)) {
  734. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  735. }
  736. return this;
  737. };
  738. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  739. this._valueCache[uniformName] = null;
  740. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  741. return this;
  742. };
  743. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  744. this._valueCache[uniformName] = null;
  745. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  746. return this;
  747. };
  748. Effect.prototype.setFloat = function (uniformName, value) {
  749. var cache = this._valueCache[uniformName];
  750. if (cache !== undefined && cache === value)
  751. return this;
  752. this._valueCache[uniformName] = value;
  753. this._engine.setFloat(this.getUniform(uniformName), value);
  754. return this;
  755. };
  756. Effect.prototype.setBool = function (uniformName, bool) {
  757. var cache = this._valueCache[uniformName];
  758. if (cache !== undefined && cache === bool)
  759. return this;
  760. this._valueCache[uniformName] = bool;
  761. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  762. return this;
  763. };
  764. Effect.prototype.setVector2 = function (uniformName, vector2) {
  765. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  766. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  767. }
  768. return this;
  769. };
  770. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  771. if (this._cacheFloat2(uniformName, x, y)) {
  772. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  773. }
  774. return this;
  775. };
  776. Effect.prototype.setVector3 = function (uniformName, vector3) {
  777. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  778. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  783. if (this._cacheFloat3(uniformName, x, y, z)) {
  784. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector4 = function (uniformName, vector4) {
  789. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  790. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  795. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  796. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setColor3 = function (uniformName, color3) {
  801. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  802. this._engine.setColor3(this.getUniform(uniformName), color3);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  807. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  808. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  809. }
  810. return this;
  811. };
  812. Effect.ResetCache = function () {
  813. Effect._baseCache = {};
  814. };
  815. Effect._uniqueIdSeed = 0;
  816. Effect._baseCache = {};
  817. // Statics
  818. Effect.ShadersStore = {};
  819. Effect.IncludesShadersStore = {};
  820. return Effect;
  821. }());
  822. BABYLON.Effect = Effect;
  823. })(BABYLON || (BABYLON = {}));
  824. //# sourceMappingURL=babylon.effect.js.map
  825. //# sourceMappingURL=babylon.types.js.map
  826. var BABYLON;
  827. (function (BABYLON) {
  828. var KeyboardEventTypes = /** @class */ (function () {
  829. function KeyboardEventTypes() {
  830. }
  831. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  832. get: function () {
  833. return KeyboardEventTypes._KEYDOWN;
  834. },
  835. enumerable: true,
  836. configurable: true
  837. });
  838. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  839. get: function () {
  840. return KeyboardEventTypes._KEYUP;
  841. },
  842. enumerable: true,
  843. configurable: true
  844. });
  845. KeyboardEventTypes._KEYDOWN = 0x01;
  846. KeyboardEventTypes._KEYUP = 0x02;
  847. return KeyboardEventTypes;
  848. }());
  849. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  850. var KeyboardInfo = /** @class */ (function () {
  851. function KeyboardInfo(type, event) {
  852. this.type = type;
  853. this.event = event;
  854. }
  855. return KeyboardInfo;
  856. }());
  857. BABYLON.KeyboardInfo = KeyboardInfo;
  858. /**
  859. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  860. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  861. */
  862. var KeyboardInfoPre = /** @class */ (function (_super) {
  863. __extends(KeyboardInfoPre, _super);
  864. function KeyboardInfoPre(type, event) {
  865. var _this = _super.call(this, type, event) || this;
  866. _this.skipOnPointerObservable = false;
  867. return _this;
  868. }
  869. return KeyboardInfoPre;
  870. }(KeyboardInfo));
  871. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.keyboardEvents.js.map
  874. var BABYLON;
  875. (function (BABYLON) {
  876. var PointerEventTypes = /** @class */ (function () {
  877. function PointerEventTypes() {
  878. }
  879. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  880. get: function () {
  881. return PointerEventTypes._POINTERDOWN;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  887. get: function () {
  888. return PointerEventTypes._POINTERUP;
  889. },
  890. enumerable: true,
  891. configurable: true
  892. });
  893. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  894. get: function () {
  895. return PointerEventTypes._POINTERMOVE;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  901. get: function () {
  902. return PointerEventTypes._POINTERWHEEL;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  908. get: function () {
  909. return PointerEventTypes._POINTERPICK;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  915. get: function () {
  916. return PointerEventTypes._POINTERTAP;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  922. get: function () {
  923. return PointerEventTypes._POINTERDOUBLETAP;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. PointerEventTypes._POINTERDOWN = 0x01;
  929. PointerEventTypes._POINTERUP = 0x02;
  930. PointerEventTypes._POINTERMOVE = 0x04;
  931. PointerEventTypes._POINTERWHEEL = 0x08;
  932. PointerEventTypes._POINTERPICK = 0x10;
  933. PointerEventTypes._POINTERTAP = 0x20;
  934. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  935. return PointerEventTypes;
  936. }());
  937. BABYLON.PointerEventTypes = PointerEventTypes;
  938. var PointerInfoBase = /** @class */ (function () {
  939. function PointerInfoBase(type, event) {
  940. this.type = type;
  941. this.event = event;
  942. }
  943. return PointerInfoBase;
  944. }());
  945. BABYLON.PointerInfoBase = PointerInfoBase;
  946. /**
  947. * This class is used to store pointer related info for the onPrePointerObservable event.
  948. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  949. */
  950. var PointerInfoPre = /** @class */ (function (_super) {
  951. __extends(PointerInfoPre, _super);
  952. function PointerInfoPre(type, event, localX, localY) {
  953. var _this = _super.call(this, type, event) || this;
  954. _this.skipOnPointerObservable = false;
  955. _this.localPosition = new BABYLON.Vector2(localX, localY);
  956. return _this;
  957. }
  958. return PointerInfoPre;
  959. }(PointerInfoBase));
  960. BABYLON.PointerInfoPre = PointerInfoPre;
  961. /**
  962. * This type contains all the data related to a pointer event in Babylon.js.
  963. * 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.
  964. */
  965. var PointerInfo = /** @class */ (function (_super) {
  966. __extends(PointerInfo, _super);
  967. function PointerInfo(type, event, pickInfo) {
  968. var _this = _super.call(this, type, event) || this;
  969. _this.pickInfo = pickInfo;
  970. return _this;
  971. }
  972. return PointerInfo;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfo = PointerInfo;
  975. })(BABYLON || (BABYLON = {}));
  976. //# sourceMappingURL=babylon.pointerEvents.js.map
  977. var BABYLON;
  978. (function (BABYLON) {
  979. BABYLON.ToGammaSpace = 1 / 2.2;
  980. BABYLON.ToLinearSpace = 2.2;
  981. BABYLON.Epsilon = 0.001;
  982. /**
  983. * Class used to hold a RBG color
  984. */
  985. var Color3 = /** @class */ (function () {
  986. /**
  987. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  988. * @param r defines the red component (between 0 and 1, default is 0)
  989. * @param g defines the green component (between 0 and 1, default is 0)
  990. * @param b defines the blue component (between 0 and 1, default is 0)
  991. */
  992. function Color3(
  993. /**
  994. * Defines the red component (between 0 and 1, default is 0)
  995. */
  996. r,
  997. /**
  998. * Defines the green component (between 0 and 1, default is 0)
  999. */
  1000. g,
  1001. /**
  1002. * Defines the blue component (between 0 and 1, default is 0)
  1003. */
  1004. b) {
  1005. if (r === void 0) { r = 0; }
  1006. if (g === void 0) { g = 0; }
  1007. if (b === void 0) { b = 0; }
  1008. this.r = r;
  1009. this.g = g;
  1010. this.b = b;
  1011. }
  1012. /**
  1013. * Creates a string with the Color3 current values
  1014. * @returns the string representation of the Color3 object
  1015. */
  1016. Color3.prototype.toString = function () {
  1017. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Color3"
  1021. * @returns "Color3"
  1022. */
  1023. Color3.prototype.getClassName = function () {
  1024. return "Color3";
  1025. };
  1026. /**
  1027. * Compute the Color3 hash code
  1028. * @returns an unique number that can be used to hash Color3 objects
  1029. */
  1030. Color3.prototype.getHashCode = function () {
  1031. var hash = this.r || 0;
  1032. hash = (hash * 397) ^ (this.g || 0);
  1033. hash = (hash * 397) ^ (this.b || 0);
  1034. return hash;
  1035. };
  1036. // Operators
  1037. /**
  1038. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1039. * @param array defines the array where to store the r,g,b components
  1040. * @param index defines an optional index in the target array to define where to start storing values
  1041. * @returns the current Color3 object
  1042. */
  1043. Color3.prototype.toArray = function (array, index) {
  1044. if (index === undefined) {
  1045. index = 0;
  1046. }
  1047. array[index] = this.r;
  1048. array[index + 1] = this.g;
  1049. array[index + 2] = this.b;
  1050. return this;
  1051. };
  1052. /**
  1053. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1054. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1055. * @returns a new {BABYLON.Color4} object
  1056. */
  1057. Color3.prototype.toColor4 = function (alpha) {
  1058. if (alpha === void 0) { alpha = 1; }
  1059. return new Color4(this.r, this.g, this.b, alpha);
  1060. };
  1061. /**
  1062. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1063. * @returns the new array
  1064. */
  1065. Color3.prototype.asArray = function () {
  1066. var result = new Array();
  1067. this.toArray(result, 0);
  1068. return result;
  1069. };
  1070. /**
  1071. * Returns the luminance value
  1072. * @returns a float value
  1073. */
  1074. Color3.prototype.toLuminance = function () {
  1075. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1076. };
  1077. /**
  1078. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1079. * @param otherColor defines the second operand
  1080. * @returns the new Color3 object
  1081. */
  1082. Color3.prototype.multiply = function (otherColor) {
  1083. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1084. };
  1085. /**
  1086. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1087. * @param otherColor defines the second operand
  1088. * @param result defines the Color3 object where to store the result
  1089. * @returns the current Color3
  1090. */
  1091. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1092. result.r = this.r * otherColor.r;
  1093. result.g = this.g * otherColor.g;
  1094. result.b = this.b * otherColor.b;
  1095. return this;
  1096. };
  1097. /**
  1098. * Determines equality between Color3 objects
  1099. * @param otherColor defines the second operand
  1100. * @returns true if the rgb values are equal to the passed ones
  1101. */
  1102. Color3.prototype.equals = function (otherColor) {
  1103. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1104. };
  1105. /**
  1106. * Determines equality between the current Color3 object and a set of r,b,g values
  1107. * @param r defines the red component to check
  1108. * @param g defines the green component to check
  1109. * @param b defines the blue component to check
  1110. * @returns true if the rgb values are equal to the passed ones
  1111. */
  1112. Color3.prototype.equalsFloats = function (r, g, b) {
  1113. return this.r === r && this.g === g && this.b === b;
  1114. };
  1115. /**
  1116. * Multiplies in place each rgb value by scale
  1117. * @param scale defines the scaling factor
  1118. * @returns the updated Color3.
  1119. */
  1120. Color3.prototype.scale = function (scale) {
  1121. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1122. };
  1123. /**
  1124. * Multiplies the rgb values by scale and stores the result into "result"
  1125. * @param scale defines the scaling factor
  1126. * @param result defines the Color3 object where to store the result
  1127. * @returns the unmodified current Color3.
  1128. */
  1129. Color3.prototype.scaleToRef = function (scale, result) {
  1130. result.r = this.r * scale;
  1131. result.g = this.g * scale;
  1132. result.b = this.b * scale;
  1133. return this;
  1134. };
  1135. /**
  1136. * Clamps the rgb values by the min and max values and stores the result into "result"
  1137. * @param min defines minimum clamping value (default is 0)
  1138. * @param max defines maximum clamping value (default is 1)
  1139. * @param result defines color to store the result into
  1140. * @returns the original Color3
  1141. */
  1142. Color3.prototype.clampToRef = function (min, max, result) {
  1143. if (min === void 0) { min = 0; }
  1144. if (max === void 0) { max = 1; }
  1145. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1146. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1147. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1148. return this;
  1149. };
  1150. /**
  1151. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1152. * @param otherColor defines the second operand
  1153. * @returns the new Color3
  1154. */
  1155. Color3.prototype.add = function (otherColor) {
  1156. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1157. };
  1158. /**
  1159. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1160. * @param otherColor defines the second operand
  1161. * @param result defines Color3 object to store the result into
  1162. * @returns the unmodified current Color3
  1163. */
  1164. Color3.prototype.addToRef = function (otherColor, result) {
  1165. result.r = this.r + otherColor.r;
  1166. result.g = this.g + otherColor.g;
  1167. result.b = this.b + otherColor.b;
  1168. return this;
  1169. };
  1170. /**
  1171. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1172. * @param otherColor defines the second operand
  1173. * @returns the new Color3
  1174. */
  1175. Color3.prototype.subtract = function (otherColor) {
  1176. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1177. };
  1178. /**
  1179. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1180. * @param otherColor defines the second operand
  1181. * @param result defines Color3 object to store the result into
  1182. * @returns the unmodified current Color3
  1183. */
  1184. Color3.prototype.subtractToRef = function (otherColor, result) {
  1185. result.r = this.r - otherColor.r;
  1186. result.g = this.g - otherColor.g;
  1187. result.b = this.b - otherColor.b;
  1188. return this;
  1189. };
  1190. /**
  1191. * Copy the current object
  1192. * @returns a new Color3 copied the current one
  1193. */
  1194. Color3.prototype.clone = function () {
  1195. return new Color3(this.r, this.g, this.b);
  1196. };
  1197. /**
  1198. * Copies the rgb values from the source in the current Color3
  1199. * @param source defines the source Color3 object
  1200. * @returns the updated Color3 object
  1201. */
  1202. Color3.prototype.copyFrom = function (source) {
  1203. this.r = source.r;
  1204. this.g = source.g;
  1205. this.b = source.b;
  1206. return this;
  1207. };
  1208. /**
  1209. * Updates the Color3 rgb values from the passed floats
  1210. * @param r defines the red component to read from
  1211. * @param g defines the green component to read from
  1212. * @param b defines the blue component to read from
  1213. * @returns the current Color3 object
  1214. */
  1215. Color3.prototype.copyFromFloats = function (r, g, b) {
  1216. this.r = r;
  1217. this.g = g;
  1218. this.b = b;
  1219. return this;
  1220. };
  1221. /**
  1222. * Updates the Color3 rgb values from the passed floats
  1223. * @param r defines the red component to read from
  1224. * @param g defines the green component to read from
  1225. * @param b defines the blue component to read from
  1226. * @returns the current Color3 object
  1227. */
  1228. Color3.prototype.set = function (r, g, b) {
  1229. return this.copyFromFloats(r, g, b);
  1230. };
  1231. /**
  1232. * Compute the Color3 hexadecimal code as a string
  1233. * @returns a string containing the hexadecimal representation of the Color3 object
  1234. */
  1235. Color3.prototype.toHexString = function () {
  1236. var intR = (this.r * 255) | 0;
  1237. var intG = (this.g * 255) | 0;
  1238. var intB = (this.b * 255) | 0;
  1239. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1240. };
  1241. /**
  1242. * Computes a new Color3 converted from the current one to linear space
  1243. * @returns a new Color3 object
  1244. */
  1245. Color3.prototype.toLinearSpace = function () {
  1246. var convertedColor = new Color3();
  1247. this.toLinearSpaceToRef(convertedColor);
  1248. return convertedColor;
  1249. };
  1250. /**
  1251. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1252. * @param convertedColor defines the Color3 object where to store the linear space version
  1253. * @returns the unmodified Color3
  1254. */
  1255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1259. return this;
  1260. };
  1261. /**
  1262. * Computes a new Color3 converted from the current one to gamma space
  1263. * @returns a new Color3 object
  1264. */
  1265. Color3.prototype.toGammaSpace = function () {
  1266. var convertedColor = new Color3();
  1267. this.toGammaSpaceToRef(convertedColor);
  1268. return convertedColor;
  1269. };
  1270. /**
  1271. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1272. * @param convertedColor defines the Color3 object where to store the gamma space version
  1273. * @returns the unmodified Color3
  1274. */
  1275. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1276. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1277. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1278. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1279. return this;
  1280. };
  1281. // Statics
  1282. /**
  1283. * Creates a new Color3 from the string containing valid hexadecimal values
  1284. * @param hex defines a string containing valid hexadecimal values
  1285. * @returns a new Color3 object
  1286. */
  1287. Color3.FromHexString = function (hex) {
  1288. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1289. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1290. return new Color3(0, 0, 0);
  1291. }
  1292. var r = parseInt(hex.substring(1, 3), 16);
  1293. var g = parseInt(hex.substring(3, 5), 16);
  1294. var b = parseInt(hex.substring(5, 7), 16);
  1295. return Color3.FromInts(r, g, b);
  1296. };
  1297. /**
  1298. * Creates a new Vector3 from the starting index of the passed array
  1299. * @param array defines the source array
  1300. * @param offset defines an offset in the source array
  1301. * @returns a new Color3 object
  1302. */
  1303. Color3.FromArray = function (array, offset) {
  1304. if (offset === void 0) { offset = 0; }
  1305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1306. };
  1307. /**
  1308. * Creates a new Color3 from integer values (< 256)
  1309. * @param r defines the red component to read from (value between 0 and 255)
  1310. * @param g defines the green component to read from (value between 0 and 255)
  1311. * @param b defines the blue component to read from (value between 0 and 255)
  1312. * @returns a new Color3 object
  1313. */
  1314. Color3.FromInts = function (r, g, b) {
  1315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1316. };
  1317. /**
  1318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1319. * @param start defines the start Color3 value
  1320. * @param end defines the end Color3 value
  1321. * @param amount defines the gradient value between start and end
  1322. * @returns a new Color3 object
  1323. */
  1324. Color3.Lerp = function (start, end, amount) {
  1325. var r = start.r + ((end.r - start.r) * amount);
  1326. var g = start.g + ((end.g - start.g) * amount);
  1327. var b = start.b + ((end.b - start.b) * amount);
  1328. return new Color3(r, g, b);
  1329. };
  1330. /**
  1331. * Returns a Color3 value containing a red color
  1332. * @returns a new Color3 object
  1333. */
  1334. Color3.Red = function () { return new Color3(1, 0, 0); };
  1335. /**
  1336. * Returns a Color3 value containing a green color
  1337. * @returns a new Color3 object
  1338. */
  1339. Color3.Green = function () { return new Color3(0, 1, 0); };
  1340. /**
  1341. * Returns a Color3 value containing a blue color
  1342. * @returns a new Color3 object
  1343. */
  1344. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1345. /**
  1346. * Returns a Color3 value containing a black color
  1347. * @returns a new Color3 object
  1348. */
  1349. Color3.Black = function () { return new Color3(0, 0, 0); };
  1350. /**
  1351. * Returns a Color3 value containing a white color
  1352. * @returns a new Color3 object
  1353. */
  1354. Color3.White = function () { return new Color3(1, 1, 1); };
  1355. /**
  1356. * Returns a Color3 value containing a purple color
  1357. * @returns a new Color3 object
  1358. */
  1359. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1360. /**
  1361. * Returns a Color3 value containing a magenta color
  1362. * @returns a new Color3 object
  1363. */
  1364. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1365. /**
  1366. * Returns a Color3 value containing a yellow color
  1367. * @returns a new Color3 object
  1368. */
  1369. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1370. /**
  1371. * Returns a Color3 value containing a gray color
  1372. * @returns a new Color3 object
  1373. */
  1374. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1375. /**
  1376. * Returns a Color3 value containing a teal color
  1377. * @returns a new Color3 object
  1378. */
  1379. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1380. /**
  1381. * Returns a Color3 value containing a random color
  1382. * @returns a new Color3 object
  1383. */
  1384. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1385. return Color3;
  1386. }());
  1387. BABYLON.Color3 = Color3;
  1388. /**
  1389. * Class used to hold a RBGA color
  1390. */
  1391. var Color4 = /** @class */ (function () {
  1392. /**
  1393. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1394. * @param r defines the red component (between 0 and 1, default is 0)
  1395. * @param g defines the green component (between 0 and 1, default is 0)
  1396. * @param b defines the blue component (between 0 and 1, default is 0)
  1397. * @param a defines the alpha component (between 0 and 1, default is 1)
  1398. */
  1399. function Color4(
  1400. /**
  1401. * Defines the red component (between 0 and 1, default is 0)
  1402. */
  1403. r,
  1404. /**
  1405. * Defines the green component (between 0 and 1, default is 0)
  1406. */
  1407. g,
  1408. /**
  1409. * Defines the blue component (between 0 and 1, default is 0)
  1410. */
  1411. b,
  1412. /**
  1413. * Defines the alpha component (between 0 and 1, default is 1)
  1414. */
  1415. a) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. if (a === void 0) { a = 1; }
  1420. this.r = r;
  1421. this.g = g;
  1422. this.b = b;
  1423. this.a = a;
  1424. }
  1425. // Operators
  1426. /**
  1427. * Adds in place the passed Color4 values to the current Color4 object
  1428. * @param right defines the second operand
  1429. * @returns the current updated Color4 object
  1430. */
  1431. Color4.prototype.addInPlace = function (right) {
  1432. this.r += right.r;
  1433. this.g += right.g;
  1434. this.b += right.b;
  1435. this.a += right.a;
  1436. return this;
  1437. };
  1438. /**
  1439. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1440. * @returns the new array
  1441. */
  1442. Color4.prototype.asArray = function () {
  1443. var result = new Array();
  1444. this.toArray(result, 0);
  1445. return result;
  1446. };
  1447. /**
  1448. * Stores from the starting index in the passed array the Color4 successive values
  1449. * @param array defines the array where to store the r,g,b components
  1450. * @param index defines an optional index in the target array to define where to start storing values
  1451. * @returns the current Color4 object
  1452. */
  1453. Color4.prototype.toArray = function (array, index) {
  1454. if (index === undefined) {
  1455. index = 0;
  1456. }
  1457. array[index] = this.r;
  1458. array[index + 1] = this.g;
  1459. array[index + 2] = this.b;
  1460. array[index + 3] = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1465. * @param right defines the second operand
  1466. * @returns a new Color4 object
  1467. */
  1468. Color4.prototype.add = function (right) {
  1469. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1470. };
  1471. /**
  1472. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1473. * @param right defines the second operand
  1474. * @returns a new Color4 object
  1475. */
  1476. Color4.prototype.subtract = function (right) {
  1477. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1478. };
  1479. /**
  1480. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1481. * @param right defines the second operand
  1482. * @param result defines the Color4 object where to store the result
  1483. * @returns the current Color4 object
  1484. */
  1485. Color4.prototype.subtractToRef = function (right, result) {
  1486. result.r = this.r - right.r;
  1487. result.g = this.g - right.g;
  1488. result.b = this.b - right.b;
  1489. result.a = this.a - right.a;
  1490. return this;
  1491. };
  1492. /**
  1493. * Creates a new Color4 with the current Color4 values multiplied by scale
  1494. * @param scale defines the scaling factor to apply
  1495. * @returns a new Color4 object
  1496. */
  1497. Color4.prototype.scale = function (scale) {
  1498. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1499. };
  1500. /**
  1501. * Multiplies the current Color4 values by scale and stores the result in "result"
  1502. * @param scale defines the scaling factor to apply
  1503. * @param result defines the Color4 object where to store the result
  1504. * @returns the current Color4.
  1505. */
  1506. Color4.prototype.scaleToRef = function (scale, result) {
  1507. result.r = this.r * scale;
  1508. result.g = this.g * scale;
  1509. result.b = this.b * scale;
  1510. result.a = this.a * scale;
  1511. return this;
  1512. };
  1513. /**
  1514. * Clamps the rgb values by the min and max values and stores the result into "result"
  1515. * @param min defines minimum clamping value (default is 0)
  1516. * @param max defines maximum clamping value (default is 1)
  1517. * @param result defines color to store the result into.
  1518. * @returns the cuurent Color4
  1519. */
  1520. Color4.prototype.clampToRef = function (min, max, result) {
  1521. if (min === void 0) { min = 0; }
  1522. if (max === void 0) { max = 1; }
  1523. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1524. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1525. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1526. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1527. return this;
  1528. };
  1529. /**
  1530. * Multipy an Color4 value by another and return a new Color4 object
  1531. * @param color defines the Color4 value to multiply by
  1532. * @returns a new Color4 object
  1533. */
  1534. Color4.prototype.multiply = function (color) {
  1535. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1536. };
  1537. /**
  1538. * Multipy a Color4 value by another and push the result in a reference value
  1539. * @param color defines the Color4 value to multiply by
  1540. * @param result defines the Color4 to fill the result in
  1541. * @returns the result Color4
  1542. */
  1543. Color4.prototype.multiplyToRef = function (color, result) {
  1544. result.r = this.r * color.r;
  1545. result.g = this.g * color.g;
  1546. result.b = this.b * color.b;
  1547. result.a = this.a * color.a;
  1548. return result;
  1549. };
  1550. /**
  1551. * Creates a string with the Color4 current values
  1552. * @returns the string representation of the Color4 object
  1553. */
  1554. Color4.prototype.toString = function () {
  1555. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1556. };
  1557. /**
  1558. * Returns the string "Color4"
  1559. * @returns "Color4"
  1560. */
  1561. Color4.prototype.getClassName = function () {
  1562. return "Color4";
  1563. };
  1564. /**
  1565. * Compute the Color4 hash code
  1566. * @returns an unique number that can be used to hash Color4 objects
  1567. */
  1568. Color4.prototype.getHashCode = function () {
  1569. var hash = this.r || 0;
  1570. hash = (hash * 397) ^ (this.g || 0);
  1571. hash = (hash * 397) ^ (this.b || 0);
  1572. hash = (hash * 397) ^ (this.a || 0);
  1573. return hash;
  1574. };
  1575. /**
  1576. * Creates a new Color4 copied from the current one
  1577. * @returns a new Color4 object
  1578. */
  1579. Color4.prototype.clone = function () {
  1580. return new Color4(this.r, this.g, this.b, this.a);
  1581. };
  1582. /**
  1583. * Copies the passed Color4 values into the current one
  1584. * @param source defines the source Color4 object
  1585. * @returns the current updated Color4 object
  1586. */
  1587. Color4.prototype.copyFrom = function (source) {
  1588. this.r = source.r;
  1589. this.g = source.g;
  1590. this.b = source.b;
  1591. this.a = source.a;
  1592. return this;
  1593. };
  1594. /**
  1595. * Copies the passed float values into the current one
  1596. * @param r defines the red component to read from
  1597. * @param g defines the green component to read from
  1598. * @param b defines the blue component to read from
  1599. * @param a defines the alpha component to read from
  1600. * @returns the current updated Color4 object
  1601. */
  1602. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1603. this.r = r;
  1604. this.g = g;
  1605. this.b = b;
  1606. this.a = a;
  1607. return this;
  1608. };
  1609. /**
  1610. * Copies the passed float values into the current one
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @param a defines the alpha component to read from
  1615. * @returns the current updated Color4 object
  1616. */
  1617. Color4.prototype.set = function (r, g, b, a) {
  1618. return this.copyFromFloats(r, g, b, a);
  1619. };
  1620. /**
  1621. * Compute the Color4 hexadecimal code as a string
  1622. * @returns a string containing the hexadecimal representation of the Color4 object
  1623. */
  1624. Color4.prototype.toHexString = function () {
  1625. var intR = (this.r * 255) | 0;
  1626. var intG = (this.g * 255) | 0;
  1627. var intB = (this.b * 255) | 0;
  1628. var intA = (this.a * 255) | 0;
  1629. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1630. };
  1631. /**
  1632. * Computes a new Color4 converted from the current one to linear space
  1633. * @returns a new Color4 object
  1634. */
  1635. Color4.prototype.toLinearSpace = function () {
  1636. var convertedColor = new Color4();
  1637. this.toLinearSpaceToRef(convertedColor);
  1638. return convertedColor;
  1639. };
  1640. /**
  1641. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1642. * @param convertedColor defines the Color4 object where to store the linear space version
  1643. * @returns the unmodified Color4
  1644. */
  1645. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1646. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1647. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1648. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1649. convertedColor.a = this.a;
  1650. return this;
  1651. };
  1652. /**
  1653. * Computes a new Color4 converted from the current one to gamma space
  1654. * @returns a new Color4 object
  1655. */
  1656. Color4.prototype.toGammaSpace = function () {
  1657. var convertedColor = new Color4();
  1658. this.toGammaSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color4 object where to store the gamma space version
  1664. * @returns the unmodified Color4
  1665. */
  1666. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1670. convertedColor.a = this.a;
  1671. return this;
  1672. };
  1673. // Statics
  1674. /**
  1675. * Creates a new Color4 from the string containing valid hexadecimal values
  1676. * @param hex defines a string containing valid hexadecimal values
  1677. * @returns a new Color4 object
  1678. */
  1679. Color4.FromHexString = function (hex) {
  1680. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1681. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1682. return new Color4(0.0, 0.0, 0.0, 0.0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. var a = parseInt(hex.substring(7, 9), 16);
  1688. return Color4.FromInts(r, g, b, a);
  1689. };
  1690. /**
  1691. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1692. * @param left defines the start value
  1693. * @param right defines the end value
  1694. * @param amount defines the gradient factor
  1695. * @returns a new Color4 object
  1696. */
  1697. Color4.Lerp = function (left, right, amount) {
  1698. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1699. Color4.LerpToRef(left, right, amount, result);
  1700. return result;
  1701. };
  1702. /**
  1703. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1704. * @param left defines the start value
  1705. * @param right defines the end value
  1706. * @param amount defines the gradient factor
  1707. * @param result defines the Color4 object where to store data
  1708. */
  1709. Color4.LerpToRef = function (left, right, amount, result) {
  1710. result.r = left.r + (right.r - left.r) * amount;
  1711. result.g = left.g + (right.g - left.g) * amount;
  1712. result.b = left.b + (right.b - left.b) * amount;
  1713. result.a = left.a + (right.a - left.a) * amount;
  1714. };
  1715. /**
  1716. * Creates a new Color4 from the starting index element of the passed array
  1717. * @param array defines the source array to read from
  1718. * @param offset defines the offset in the source array
  1719. * @returns a new Color4 object
  1720. */
  1721. Color4.FromArray = function (array, offset) {
  1722. if (offset === void 0) { offset = 0; }
  1723. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1724. };
  1725. /**
  1726. * Creates a new Color3 from integer values (< 256)
  1727. * @param r defines the red component to read from (value between 0 and 255)
  1728. * @param g defines the green component to read from (value between 0 and 255)
  1729. * @param b defines the blue component to read from (value between 0 and 255)
  1730. * @param a defines the alpha component to read from (value between 0 and 255)
  1731. * @returns a new Color3 object
  1732. */
  1733. Color4.FromInts = function (r, g, b, a) {
  1734. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1735. };
  1736. /**
  1737. * Check the content of a given array and convert it to an array containing RGBA data
  1738. * If the original array was already containing count * 4 values then it is returned directly
  1739. * @param colors defines the array to check
  1740. * @param count defines the number of RGBA data to expect
  1741. * @returns an array containing count * 4 values (RGBA)
  1742. */
  1743. Color4.CheckColors4 = function (colors, count) {
  1744. // Check if color3 was used
  1745. if (colors.length === count * 3) {
  1746. var colors4 = [];
  1747. for (var index = 0; index < colors.length; index += 3) {
  1748. var newIndex = (index / 3) * 4;
  1749. colors4[newIndex] = colors[index];
  1750. colors4[newIndex + 1] = colors[index + 1];
  1751. colors4[newIndex + 2] = colors[index + 2];
  1752. colors4[newIndex + 3] = 1.0;
  1753. }
  1754. return colors4;
  1755. }
  1756. return colors;
  1757. };
  1758. return Color4;
  1759. }());
  1760. BABYLON.Color4 = Color4;
  1761. var Vector2 = /** @class */ (function () {
  1762. /**
  1763. * Creates a new Vector2 from the passed x and y coordinates.
  1764. */
  1765. function Vector2(x, y) {
  1766. this.x = x;
  1767. this.y = y;
  1768. }
  1769. /**
  1770. * Returns a string with the Vector2 coordinates.
  1771. */
  1772. Vector2.prototype.toString = function () {
  1773. return "{X: " + this.x + " Y:" + this.y + "}";
  1774. };
  1775. /**
  1776. * Returns the string "Vector2"
  1777. */
  1778. Vector2.prototype.getClassName = function () {
  1779. return "Vector2";
  1780. };
  1781. /**
  1782. * Returns the Vector2 hash code as a number.
  1783. */
  1784. Vector2.prototype.getHashCode = function () {
  1785. var hash = this.x || 0;
  1786. hash = (hash * 397) ^ (this.y || 0);
  1787. return hash;
  1788. };
  1789. // Operators
  1790. /**
  1791. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1792. * Returns the Vector2.
  1793. */
  1794. Vector2.prototype.toArray = function (array, index) {
  1795. if (index === void 0) { index = 0; }
  1796. array[index] = this.x;
  1797. array[index + 1] = this.y;
  1798. return this;
  1799. };
  1800. /**
  1801. * Returns a new array with 2 elements : the Vector2 coordinates.
  1802. */
  1803. Vector2.prototype.asArray = function () {
  1804. var result = new Array();
  1805. this.toArray(result, 0);
  1806. return result;
  1807. };
  1808. /**
  1809. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1810. * Returns the updated Vector2.
  1811. */
  1812. Vector2.prototype.copyFrom = function (source) {
  1813. this.x = source.x;
  1814. this.y = source.y;
  1815. return this;
  1816. };
  1817. /**
  1818. * Sets the Vector2 coordinates with the passed floats.
  1819. * Returns the updated Vector2.
  1820. */
  1821. Vector2.prototype.copyFromFloats = function (x, y) {
  1822. this.x = x;
  1823. this.y = y;
  1824. return this;
  1825. };
  1826. /**
  1827. * Sets the Vector2 coordinates with the passed floats.
  1828. * Returns the updated Vector2.
  1829. */
  1830. Vector2.prototype.set = function (x, y) {
  1831. return this.copyFromFloats(x, y);
  1832. };
  1833. /**
  1834. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1835. */
  1836. Vector2.prototype.add = function (otherVector) {
  1837. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1838. };
  1839. /**
  1840. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1841. * Returns the Vector2.
  1842. */
  1843. Vector2.prototype.addToRef = function (otherVector, result) {
  1844. result.x = this.x + otherVector.x;
  1845. result.y = this.y + otherVector.y;
  1846. return this;
  1847. };
  1848. /**
  1849. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1850. * Returns the updated Vector2.
  1851. */
  1852. Vector2.prototype.addInPlace = function (otherVector) {
  1853. this.x += otherVector.x;
  1854. this.y += otherVector.y;
  1855. return this;
  1856. };
  1857. /**
  1858. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1859. */
  1860. Vector2.prototype.addVector3 = function (otherVector) {
  1861. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1862. };
  1863. /**
  1864. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1865. */
  1866. Vector2.prototype.subtract = function (otherVector) {
  1867. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1868. };
  1869. /**
  1870. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1871. * Returns the Vector2.
  1872. */
  1873. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1874. result.x = this.x - otherVector.x;
  1875. result.y = this.y - otherVector.y;
  1876. return this;
  1877. };
  1878. /**
  1879. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1880. * Returns the updated Vector2.
  1881. */
  1882. Vector2.prototype.subtractInPlace = function (otherVector) {
  1883. this.x -= otherVector.x;
  1884. this.y -= otherVector.y;
  1885. return this;
  1886. };
  1887. /**
  1888. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1889. * Returns the updated Vector2.
  1890. */
  1891. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1892. this.x *= otherVector.x;
  1893. this.y *= otherVector.y;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1898. */
  1899. Vector2.prototype.multiply = function (otherVector) {
  1900. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1901. };
  1902. /**
  1903. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1904. * Returns the Vector2.
  1905. */
  1906. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1907. result.x = this.x * otherVector.x;
  1908. result.y = this.y * otherVector.y;
  1909. return this;
  1910. };
  1911. /**
  1912. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1913. */
  1914. Vector2.prototype.multiplyByFloats = function (x, y) {
  1915. return new Vector2(this.x * x, this.y * y);
  1916. };
  1917. /**
  1918. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1919. */
  1920. Vector2.prototype.divide = function (otherVector) {
  1921. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1922. };
  1923. /**
  1924. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1925. * Returns the Vector2.
  1926. */
  1927. Vector2.prototype.divideToRef = function (otherVector, result) {
  1928. result.x = this.x / otherVector.x;
  1929. result.y = this.y / otherVector.y;
  1930. return this;
  1931. };
  1932. /**
  1933. * Divides the current Vector3 coordinates by the passed ones.
  1934. * Returns the updated Vector3.
  1935. */
  1936. Vector2.prototype.divideInPlace = function (otherVector) {
  1937. return this.divideToRef(otherVector, this);
  1938. };
  1939. /**
  1940. * Returns a new Vector2 with current Vector2 negated coordinates.
  1941. */
  1942. Vector2.prototype.negate = function () {
  1943. return new Vector2(-this.x, -this.y);
  1944. };
  1945. /**
  1946. * Multiply the Vector2 coordinates by scale.
  1947. * Returns the updated Vector2.
  1948. */
  1949. Vector2.prototype.scaleInPlace = function (scale) {
  1950. this.x *= scale;
  1951. this.y *= scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1956. */
  1957. Vector2.prototype.scale = function (scale) {
  1958. return new Vector2(this.x * scale, this.y * scale);
  1959. };
  1960. /**
  1961. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1962. */
  1963. Vector2.prototype.equals = function (otherVector) {
  1964. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1965. };
  1966. /**
  1967. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1968. */
  1969. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1970. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1971. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1972. };
  1973. // Properties
  1974. /**
  1975. * Returns the vector length (float).
  1976. */
  1977. Vector2.prototype.length = function () {
  1978. return Math.sqrt(this.x * this.x + this.y * this.y);
  1979. };
  1980. /**
  1981. * Returns the vector squared length (float);
  1982. */
  1983. Vector2.prototype.lengthSquared = function () {
  1984. return (this.x * this.x + this.y * this.y);
  1985. };
  1986. // Methods
  1987. /**
  1988. * Normalize the vector.
  1989. * Returns the updated Vector2.
  1990. */
  1991. Vector2.prototype.normalize = function () {
  1992. var len = this.length();
  1993. if (len === 0)
  1994. return this;
  1995. var num = 1.0 / len;
  1996. this.x *= num;
  1997. this.y *= num;
  1998. return this;
  1999. };
  2000. /**
  2001. * Returns a new Vector2 copied from the Vector2.
  2002. */
  2003. Vector2.prototype.clone = function () {
  2004. return new Vector2(this.x, this.y);
  2005. };
  2006. // Statics
  2007. /**
  2008. * Returns a new Vector2(0, 0)
  2009. */
  2010. Vector2.Zero = function () {
  2011. return new Vector2(0, 0);
  2012. };
  2013. /**
  2014. * Returns a new Vector2(1, 1)
  2015. */
  2016. Vector2.One = function () {
  2017. return new Vector2(1, 1);
  2018. };
  2019. /**
  2020. * Returns a new Vector2 set from the passed index element of the passed array.
  2021. */
  2022. Vector2.FromArray = function (array, offset) {
  2023. if (offset === void 0) { offset = 0; }
  2024. return new Vector2(array[offset], array[offset + 1]);
  2025. };
  2026. /**
  2027. * Sets "result" from the passed index element of the passed array.
  2028. */
  2029. Vector2.FromArrayToRef = function (array, offset, result) {
  2030. result.x = array[offset];
  2031. result.y = array[offset + 1];
  2032. };
  2033. /**
  2034. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2035. */
  2036. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2037. var squared = amount * amount;
  2038. var cubed = amount * squared;
  2039. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2040. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2041. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2042. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2043. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2044. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2045. return new Vector2(x, y);
  2046. };
  2047. /**
  2048. * 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".
  2049. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2050. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2051. */
  2052. Vector2.Clamp = function (value, min, max) {
  2053. var x = value.x;
  2054. x = (x > max.x) ? max.x : x;
  2055. x = (x < min.x) ? min.x : x;
  2056. var y = value.y;
  2057. y = (y > max.y) ? max.y : y;
  2058. y = (y < min.y) ? min.y : y;
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2063. */
  2064. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2065. var squared = amount * amount;
  2066. var cubed = amount * squared;
  2067. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2068. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2069. var part3 = (cubed - (2.0 * squared)) + amount;
  2070. var part4 = cubed - squared;
  2071. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2072. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2077. */
  2078. Vector2.Lerp = function (start, end, amount) {
  2079. var x = start.x + ((end.x - start.x) * amount);
  2080. var y = start.y + ((end.y - start.y) * amount);
  2081. return new Vector2(x, y);
  2082. };
  2083. /**
  2084. * Returns the dot product (float) of the vector "left" and the vector "right".
  2085. */
  2086. Vector2.Dot = function (left, right) {
  2087. return left.x * right.x + left.y * right.y;
  2088. };
  2089. /**
  2090. * Returns a new Vector2 equal to the normalized passed vector.
  2091. */
  2092. Vector2.Normalize = function (vector) {
  2093. var newVector = vector.clone();
  2094. newVector.normalize();
  2095. return newVector;
  2096. };
  2097. /**
  2098. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2099. */
  2100. Vector2.Minimize = function (left, right) {
  2101. var x = (left.x < right.x) ? left.x : right.x;
  2102. var y = (left.y < right.y) ? left.y : right.y;
  2103. return new Vector2(x, y);
  2104. };
  2105. /**
  2106. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2107. */
  2108. Vector2.Maximize = function (left, right) {
  2109. var x = (left.x > right.x) ? left.x : right.x;
  2110. var y = (left.y > right.y) ? left.y : right.y;
  2111. return new Vector2(x, y);
  2112. };
  2113. /**
  2114. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2115. */
  2116. Vector2.Transform = function (vector, transformation) {
  2117. var r = Vector2.Zero();
  2118. Vector2.TransformToRef(vector, transformation, r);
  2119. return r;
  2120. };
  2121. /**
  2122. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2123. */
  2124. Vector2.TransformToRef = function (vector, transformation, result) {
  2125. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2126. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2127. result.x = x;
  2128. result.y = y;
  2129. };
  2130. /**
  2131. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2132. */
  2133. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2134. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2135. var sign = a < 0 ? -1 : 1;
  2136. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2137. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2138. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2139. };
  2140. /**
  2141. * Returns the distance (float) between the vectors "value1" and "value2".
  2142. */
  2143. Vector2.Distance = function (value1, value2) {
  2144. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2145. };
  2146. /**
  2147. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2148. */
  2149. Vector2.DistanceSquared = function (value1, value2) {
  2150. var x = value1.x - value2.x;
  2151. var y = value1.y - value2.y;
  2152. return (x * x) + (y * y);
  2153. };
  2154. /**
  2155. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Center = function (value1, value2) {
  2158. var center = value1.add(value2);
  2159. center.scaleInPlace(0.5);
  2160. return center;
  2161. };
  2162. /**
  2163. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2164. */
  2165. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2166. var l2 = Vector2.DistanceSquared(segA, segB);
  2167. if (l2 === 0.0) {
  2168. return Vector2.Distance(p, segA);
  2169. }
  2170. var v = segB.subtract(segA);
  2171. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2172. var proj = segA.add(v.multiplyByFloats(t, t));
  2173. return Vector2.Distance(p, proj);
  2174. };
  2175. return Vector2;
  2176. }());
  2177. BABYLON.Vector2 = Vector2;
  2178. var Vector3 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2181. * A Vector3 is the main object used in 3D geometry.
  2182. * It can represent etiher the coordinates of a point the space, either a direction.
  2183. */
  2184. function Vector3(x, y, z) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. }
  2189. /**
  2190. * Returns a string with the Vector3 coordinates.
  2191. */
  2192. Vector3.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2194. };
  2195. /**
  2196. * Returns the string "Vector3"
  2197. */
  2198. Vector3.prototype.getClassName = function () {
  2199. return "Vector3";
  2200. };
  2201. /**
  2202. * Returns the Vector hash code.
  2203. */
  2204. Vector3.prototype.getHashCode = function () {
  2205. var hash = this.x || 0;
  2206. hash = (hash * 397) ^ (this.y || 0);
  2207. hash = (hash * 397) ^ (this.z || 0);
  2208. return hash;
  2209. };
  2210. // Operators
  2211. /**
  2212. * Returns a new array with three elements : the coordinates the Vector3.
  2213. */
  2214. Vector3.prototype.asArray = function () {
  2215. var result = [];
  2216. this.toArray(result, 0);
  2217. return result;
  2218. };
  2219. /**
  2220. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2221. * Returns the Vector3.
  2222. */
  2223. Vector3.prototype.toArray = function (array, index) {
  2224. if (index === void 0) { index = 0; }
  2225. array[index] = this.x;
  2226. array[index + 1] = this.y;
  2227. array[index + 2] = this.z;
  2228. return this;
  2229. };
  2230. /**
  2231. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2232. */
  2233. Vector3.prototype.toQuaternion = function () {
  2234. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2235. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2236. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2237. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2238. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2239. var cosy = Math.cos(this.y * 0.5);
  2240. var siny = Math.sin(this.y * 0.5);
  2241. result.x = coszMinusx * siny;
  2242. result.y = -sinzMinusx * siny;
  2243. result.z = sinxPlusz * cosy;
  2244. result.w = cosxPlusz * cosy;
  2245. return result;
  2246. };
  2247. /**
  2248. * Adds the passed vector to the current Vector3.
  2249. * Returns the updated Vector3.
  2250. */
  2251. Vector3.prototype.addInPlace = function (otherVector) {
  2252. this.x += otherVector.x;
  2253. this.y += otherVector.y;
  2254. this.z += otherVector.z;
  2255. return this;
  2256. };
  2257. /**
  2258. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2259. */
  2260. Vector3.prototype.add = function (otherVector) {
  2261. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2262. };
  2263. /**
  2264. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2265. * Returns the current Vector3.
  2266. */
  2267. Vector3.prototype.addToRef = function (otherVector, result) {
  2268. result.x = this.x + otherVector.x;
  2269. result.y = this.y + otherVector.y;
  2270. result.z = this.z + otherVector.z;
  2271. return this;
  2272. };
  2273. /**
  2274. * Subtract the passed vector from the current Vector3.
  2275. * Returns the updated Vector3.
  2276. */
  2277. Vector3.prototype.subtractInPlace = function (otherVector) {
  2278. this.x -= otherVector.x;
  2279. this.y -= otherVector.y;
  2280. this.z -= otherVector.z;
  2281. return this;
  2282. };
  2283. /**
  2284. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2285. */
  2286. Vector3.prototype.subtract = function (otherVector) {
  2287. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2288. };
  2289. /**
  2290. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2291. * Returns the current Vector3.
  2292. */
  2293. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2294. result.x = this.x - otherVector.x;
  2295. result.y = this.y - otherVector.y;
  2296. result.z = this.z - otherVector.z;
  2297. return this;
  2298. };
  2299. /**
  2300. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2301. */
  2302. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2303. return new Vector3(this.x - x, this.y - y, this.z - z);
  2304. };
  2305. /**
  2306. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2307. * Returns the current Vector3.
  2308. */
  2309. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2310. result.x = this.x - x;
  2311. result.y = this.y - y;
  2312. result.z = this.z - z;
  2313. return this;
  2314. };
  2315. /**
  2316. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2317. */
  2318. Vector3.prototype.negate = function () {
  2319. return new Vector3(-this.x, -this.y, -this.z);
  2320. };
  2321. /**
  2322. * Multiplies the Vector3 coordinates by the float "scale".
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.scaleInPlace = function (scale) {
  2326. this.x *= scale;
  2327. this.y *= scale;
  2328. this.z *= scale;
  2329. return this;
  2330. };
  2331. /**
  2332. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2333. */
  2334. Vector3.prototype.scale = function (scale) {
  2335. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2336. };
  2337. /**
  2338. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2339. * Returns the current Vector3.
  2340. */
  2341. Vector3.prototype.scaleToRef = function (scale, result) {
  2342. result.x = this.x * scale;
  2343. result.y = this.y * scale;
  2344. result.z = this.z * scale;
  2345. return this;
  2346. };
  2347. /**
  2348. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2349. */
  2350. Vector3.prototype.equals = function (otherVector) {
  2351. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2352. };
  2353. /**
  2354. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2355. */
  2356. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2357. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2358. 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);
  2359. };
  2360. /**
  2361. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2362. */
  2363. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2364. return this.x === x && this.y === y && this.z === z;
  2365. };
  2366. /**
  2367. * Muliplies the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2371. this.x *= otherVector.x;
  2372. this.y *= otherVector.y;
  2373. this.z *= otherVector.z;
  2374. return this;
  2375. };
  2376. /**
  2377. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2378. */
  2379. Vector3.prototype.multiply = function (otherVector) {
  2380. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2381. };
  2382. /**
  2383. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2384. * Returns the current Vector3.
  2385. */
  2386. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. result.z = this.z * otherVector.z;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2394. */
  2395. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2396. return new Vector3(this.x * x, this.y * y, this.z * z);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2400. */
  2401. Vector3.prototype.divide = function (otherVector) {
  2402. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2403. };
  2404. /**
  2405. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2406. * Returns the current Vector3.
  2407. */
  2408. Vector3.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. result.z = this.z / otherVector.z;
  2412. return this;
  2413. };
  2414. /**
  2415. * Divides the current Vector3 coordinates by the passed ones.
  2416. * Returns the updated Vector3.
  2417. */
  2418. Vector3.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2423. * Returns the updated Vector3.
  2424. */
  2425. Vector3.prototype.MinimizeInPlace = function (other) {
  2426. if (other.x < this.x)
  2427. this.x = other.x;
  2428. if (other.y < this.y)
  2429. this.y = other.y;
  2430. if (other.z < this.z)
  2431. this.z = other.z;
  2432. return this;
  2433. };
  2434. /**
  2435. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2436. * Returns the updated Vector3.
  2437. */
  2438. Vector3.prototype.MaximizeInPlace = function (other) {
  2439. if (other.x > this.x)
  2440. this.x = other.x;
  2441. if (other.y > this.y)
  2442. this.y = other.y;
  2443. if (other.z > this.z)
  2444. this.z = other.z;
  2445. return this;
  2446. };
  2447. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2448. /**
  2449. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2450. */
  2451. get: function () {
  2452. var absX = Math.abs(this.x);
  2453. var absY = Math.abs(this.y);
  2454. if (absX !== absY) {
  2455. return true;
  2456. }
  2457. var absZ = Math.abs(this.z);
  2458. if (absX !== absZ) {
  2459. return true;
  2460. }
  2461. if (absY !== absZ) {
  2462. return true;
  2463. }
  2464. return false;
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. // Properties
  2470. /**
  2471. * Returns the length of the Vector3 (float).
  2472. */
  2473. Vector3.prototype.length = function () {
  2474. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2475. };
  2476. /**
  2477. * Returns the squared length of the Vector3 (float).
  2478. */
  2479. Vector3.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2481. };
  2482. /**
  2483. * Normalize the current Vector3.
  2484. * Returns the updated Vector3.
  2485. * /!\ In place operation.
  2486. */
  2487. Vector3.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0 || len === 1.0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. this.z *= num;
  2495. return this;
  2496. };
  2497. /**
  2498. * Normalize the current Vector3 to a new vector.
  2499. * @returns the new Vector3.
  2500. */
  2501. Vector3.prototype.normalizeToNew = function () {
  2502. var normalized = new Vector3(0, 0, 0);
  2503. this.normalizeToRef(normalized);
  2504. return normalized;
  2505. };
  2506. /**
  2507. * Normalize the current Vector3 to the reference.
  2508. * @param the reference to update.
  2509. * @returns the updated Vector3.
  2510. */
  2511. Vector3.prototype.normalizeToRef = function (reference) {
  2512. var len = this.length();
  2513. if (len === 0 || len === 1.0) {
  2514. reference.set(this.x, this.y, this.z);
  2515. return reference;
  2516. }
  2517. var scale = 1.0 / len;
  2518. this.scaleToRef(scale, reference);
  2519. return reference;
  2520. };
  2521. /**
  2522. * Returns a new Vector3 copied from the current Vector3.
  2523. */
  2524. Vector3.prototype.clone = function () {
  2525. return new Vector3(this.x, this.y, this.z);
  2526. };
  2527. /**
  2528. * Copies the passed vector coordinates to the current Vector3 ones.
  2529. * Returns the updated Vector3.
  2530. */
  2531. Vector3.prototype.copyFrom = function (source) {
  2532. this.x = source.x;
  2533. this.y = source.y;
  2534. this.z = source.z;
  2535. return this;
  2536. };
  2537. /**
  2538. * Copies the passed floats to the current Vector3 coordinates.
  2539. * Returns the updated Vector3.
  2540. */
  2541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2542. this.x = x;
  2543. this.y = y;
  2544. this.z = z;
  2545. return this;
  2546. };
  2547. /**
  2548. * Copies the passed floats to the current Vector3 coordinates.
  2549. * Returns the updated Vector3.
  2550. */
  2551. Vector3.prototype.set = function (x, y, z) {
  2552. return this.copyFromFloats(x, y, z);
  2553. };
  2554. // Statics
  2555. /**
  2556. *
  2557. */
  2558. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2559. var d0 = Vector3.Dot(vector0, axis) - size;
  2560. var d1 = Vector3.Dot(vector1, axis) - size;
  2561. var s = d0 / (d0 - d1);
  2562. return s;
  2563. };
  2564. /**
  2565. * Get angle between two vectors.
  2566. * @param vector0 angle between vector0 and vector1
  2567. * @param vector1 angle between vector0 and vector1
  2568. * @param normal direction of the normal.
  2569. * @return the angle between vector0 and vector1.
  2570. */
  2571. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2572. var v0 = vector0.clone().normalize();
  2573. var v1 = vector1.clone().normalize();
  2574. var dot = Vector3.Dot(v0, v1);
  2575. var n = Vector3.Cross(v0, v1);
  2576. if (Vector3.Dot(n, normal) > 0) {
  2577. return Math.acos(dot);
  2578. }
  2579. return -Math.acos(dot);
  2580. };
  2581. /**
  2582. * Returns a new Vector3 set from the index "offset" of the passed array.
  2583. */
  2584. Vector3.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2589. };
  2590. /**
  2591. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2592. * This function is deprecated. Use FromArray instead.
  2593. */
  2594. Vector3.FromFloatArray = function (array, offset) {
  2595. return Vector3.FromArray(array, offset);
  2596. };
  2597. /**
  2598. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2599. */
  2600. Vector3.FromArrayToRef = function (array, offset, result) {
  2601. result.x = array[offset];
  2602. result.y = array[offset + 1];
  2603. result.z = array[offset + 2];
  2604. };
  2605. /**
  2606. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2607. * This function is deprecated. Use FromArrayToRef instead.
  2608. */
  2609. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2610. return Vector3.FromArrayToRef(array, offset, result);
  2611. };
  2612. /**
  2613. * Sets the passed vector "result" with the passed floats.
  2614. */
  2615. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2616. result.x = x;
  2617. result.y = y;
  2618. result.z = z;
  2619. };
  2620. /**
  2621. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2622. */
  2623. Vector3.Zero = function () {
  2624. return new Vector3(0.0, 0.0, 0.0);
  2625. };
  2626. /**
  2627. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2628. */
  2629. Vector3.One = function () {
  2630. return new Vector3(1.0, 1.0, 1.0);
  2631. };
  2632. /**
  2633. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2634. */
  2635. Vector3.Up = function () {
  2636. return new Vector3(0.0, 1.0, 0.0);
  2637. };
  2638. /**
  2639. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2640. */
  2641. Vector3.Forward = function () {
  2642. return new Vector3(0.0, 0.0, 1.0);
  2643. };
  2644. /**
  2645. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2646. */
  2647. Vector3.Right = function () {
  2648. return new Vector3(1.0, 0.0, 0.0);
  2649. };
  2650. /**
  2651. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2652. */
  2653. Vector3.Left = function () {
  2654. return new Vector3(-1.0, 0.0, 0.0);
  2655. };
  2656. /**
  2657. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2658. * This method computes tranformed coordinates only, not transformed direction vectors.
  2659. */
  2660. Vector3.TransformCoordinates = function (vector, transformation) {
  2661. var result = Vector3.Zero();
  2662. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2663. return result;
  2664. };
  2665. /**
  2666. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2667. * This method computes tranformed coordinates only, not transformed direction vectors.
  2668. */
  2669. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2670. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2671. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2672. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2673. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2674. result.x = x / w;
  2675. result.y = y / w;
  2676. result.z = z / w;
  2677. };
  2678. /**
  2679. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2680. * This method computes tranformed coordinates only, not transformed direction vectors.
  2681. */
  2682. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2683. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2684. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2685. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2686. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2687. result.x = rx / rw;
  2688. result.y = ry / rw;
  2689. result.z = rz / rw;
  2690. };
  2691. /**
  2692. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2693. * This methods computes transformed normalized direction vectors only.
  2694. */
  2695. Vector3.TransformNormal = function (vector, transformation) {
  2696. var result = Vector3.Zero();
  2697. Vector3.TransformNormalToRef(vector, transformation, result);
  2698. return result;
  2699. };
  2700. /**
  2701. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2702. * This methods computes transformed normalized direction vectors only.
  2703. */
  2704. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2705. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2706. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2707. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2708. result.x = x;
  2709. result.y = y;
  2710. result.z = z;
  2711. };
  2712. /**
  2713. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2714. * This methods computes transformed normalized direction vectors only.
  2715. */
  2716. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2717. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2718. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2719. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2720. };
  2721. /**
  2722. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2723. */
  2724. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2725. var squared = amount * amount;
  2726. var cubed = amount * squared;
  2727. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2728. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2729. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2730. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2731. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2732. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2733. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2734. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2735. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2736. return new Vector3(x, y, z);
  2737. };
  2738. /**
  2739. * 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".
  2740. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2741. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2742. */
  2743. Vector3.Clamp = function (value, min, max) {
  2744. var x = value.x;
  2745. x = (x > max.x) ? max.x : x;
  2746. x = (x < min.x) ? min.x : x;
  2747. var y = value.y;
  2748. y = (y > max.y) ? max.y : y;
  2749. y = (y < min.y) ? min.y : y;
  2750. var z = value.z;
  2751. z = (z > max.z) ? max.z : z;
  2752. z = (z < min.z) ? min.z : z;
  2753. return new Vector3(x, y, z);
  2754. };
  2755. /**
  2756. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2757. */
  2758. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2759. var squared = amount * amount;
  2760. var cubed = amount * squared;
  2761. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2762. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2763. var part3 = (cubed - (2.0 * squared)) + amount;
  2764. var part4 = cubed - squared;
  2765. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2766. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2767. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2768. return new Vector3(x, y, z);
  2769. };
  2770. /**
  2771. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2772. */
  2773. Vector3.Lerp = function (start, end, amount) {
  2774. var result = new Vector3(0, 0, 0);
  2775. Vector3.LerpToRef(start, end, amount, result);
  2776. return result;
  2777. };
  2778. /**
  2779. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2780. */
  2781. Vector3.LerpToRef = function (start, end, amount, result) {
  2782. result.x = start.x + ((end.x - start.x) * amount);
  2783. result.y = start.y + ((end.y - start.y) * amount);
  2784. result.z = start.z + ((end.z - start.z) * amount);
  2785. };
  2786. /**
  2787. * Returns the dot product (float) between the vectors "left" and "right".
  2788. */
  2789. Vector3.Dot = function (left, right) {
  2790. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2791. };
  2792. /**
  2793. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2794. * The cross product is then orthogonal to both "left" and "right".
  2795. */
  2796. Vector3.Cross = function (left, right) {
  2797. var result = Vector3.Zero();
  2798. Vector3.CrossToRef(left, right, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed vector "result" with the cross product of "left" and "right".
  2803. * The cross product is then orthogonal to both "left" and "right".
  2804. */
  2805. Vector3.CrossToRef = function (left, right, result) {
  2806. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2807. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2808. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2809. result.copyFrom(MathTmp.Vector3[0]);
  2810. };
  2811. /**
  2812. * Returns a new Vector3 as the normalization of the passed vector.
  2813. */
  2814. Vector3.Normalize = function (vector) {
  2815. var result = Vector3.Zero();
  2816. Vector3.NormalizeToRef(vector, result);
  2817. return result;
  2818. };
  2819. /**
  2820. * Sets the passed vector "result" with the normalization of the passed first vector.
  2821. */
  2822. Vector3.NormalizeToRef = function (vector, result) {
  2823. result.copyFrom(vector);
  2824. result.normalize();
  2825. };
  2826. Vector3.Project = function (vector, world, transform, viewport) {
  2827. var cw = viewport.width;
  2828. var ch = viewport.height;
  2829. var cx = viewport.x;
  2830. var cy = viewport.y;
  2831. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2832. 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);
  2833. var matrix = MathTmp.Matrix[0];
  2834. world.multiplyToRef(transform, matrix);
  2835. matrix.multiplyToRef(viewportMatrix, matrix);
  2836. return Vector3.TransformCoordinates(vector, matrix);
  2837. };
  2838. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2839. var matrix = MathTmp.Matrix[0];
  2840. world.multiplyToRef(transform, matrix);
  2841. matrix.invert();
  2842. source.x = source.x / viewportWidth * 2 - 1;
  2843. source.y = -(source.y / viewportHeight * 2 - 1);
  2844. var vector = Vector3.TransformCoordinates(source, matrix);
  2845. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2846. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2847. vector = vector.scale(1.0 / num);
  2848. }
  2849. return vector;
  2850. };
  2851. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2852. var result = Vector3.Zero();
  2853. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2854. return result;
  2855. };
  2856. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2857. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2858. };
  2859. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2860. var matrix = MathTmp.Matrix[0];
  2861. world.multiplyToRef(view, matrix);
  2862. matrix.multiplyToRef(projection, matrix);
  2863. matrix.invert();
  2864. var screenSource = MathTmp.Vector3[0];
  2865. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2866. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2867. screenSource.z = 2 * sourceZ - 1.0;
  2868. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2869. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2870. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2871. result.scaleInPlace(1.0 / num);
  2872. }
  2873. };
  2874. Vector3.Minimize = function (left, right) {
  2875. var min = left.clone();
  2876. min.MinimizeInPlace(right);
  2877. return min;
  2878. };
  2879. Vector3.Maximize = function (left, right) {
  2880. var max = left.clone();
  2881. max.MaximizeInPlace(right);
  2882. return max;
  2883. };
  2884. /**
  2885. * Returns the distance (float) between the vectors "value1" and "value2".
  2886. */
  2887. Vector3.Distance = function (value1, value2) {
  2888. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2889. };
  2890. /**
  2891. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2892. */
  2893. Vector3.DistanceSquared = function (value1, value2) {
  2894. var x = value1.x - value2.x;
  2895. var y = value1.y - value2.y;
  2896. var z = value1.z - value2.z;
  2897. return (x * x) + (y * y) + (z * z);
  2898. };
  2899. /**
  2900. * Returns a new Vector3 located at the center between "value1" and "value2".
  2901. */
  2902. Vector3.Center = function (value1, value2) {
  2903. var center = value1.add(value2);
  2904. center.scaleInPlace(0.5);
  2905. return center;
  2906. };
  2907. /**
  2908. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2909. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2910. * to something in order to rotate it from its local system to the given target system.
  2911. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2912. * Returns a new Vector3.
  2913. */
  2914. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2915. var rotation = Vector3.Zero();
  2916. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2917. return rotation;
  2918. };
  2919. /**
  2920. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2921. */
  2922. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2923. var quat = MathTmp.Quaternion[0];
  2924. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2925. quat.toEulerAnglesToRef(ref);
  2926. };
  2927. return Vector3;
  2928. }());
  2929. BABYLON.Vector3 = Vector3;
  2930. //Vector4 class created for EulerAngle class conversion to Quaternion
  2931. var Vector4 = /** @class */ (function () {
  2932. /**
  2933. * Creates a Vector4 object from the passed floats.
  2934. */
  2935. function Vector4(x, y, z, w) {
  2936. this.x = x;
  2937. this.y = y;
  2938. this.z = z;
  2939. this.w = w;
  2940. }
  2941. /**
  2942. * Returns the string with the Vector4 coordinates.
  2943. */
  2944. Vector4.prototype.toString = function () {
  2945. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2946. };
  2947. /**
  2948. * Returns the string "Vector4".
  2949. */
  2950. Vector4.prototype.getClassName = function () {
  2951. return "Vector4";
  2952. };
  2953. /**
  2954. * Returns the Vector4 hash code.
  2955. */
  2956. Vector4.prototype.getHashCode = function () {
  2957. var hash = this.x || 0;
  2958. hash = (hash * 397) ^ (this.y || 0);
  2959. hash = (hash * 397) ^ (this.z || 0);
  2960. hash = (hash * 397) ^ (this.w || 0);
  2961. return hash;
  2962. };
  2963. // Operators
  2964. /**
  2965. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2966. */
  2967. Vector4.prototype.asArray = function () {
  2968. var result = new Array();
  2969. this.toArray(result, 0);
  2970. return result;
  2971. };
  2972. /**
  2973. * Populates the passed array from the passed index with the Vector4 coordinates.
  2974. * Returns the Vector4.
  2975. */
  2976. Vector4.prototype.toArray = function (array, index) {
  2977. if (index === undefined) {
  2978. index = 0;
  2979. }
  2980. array[index] = this.x;
  2981. array[index + 1] = this.y;
  2982. array[index + 2] = this.z;
  2983. array[index + 3] = this.w;
  2984. return this;
  2985. };
  2986. /**
  2987. * Adds the passed vector to the current Vector4.
  2988. * Returns the updated Vector4.
  2989. */
  2990. Vector4.prototype.addInPlace = function (otherVector) {
  2991. this.x += otherVector.x;
  2992. this.y += otherVector.y;
  2993. this.z += otherVector.z;
  2994. this.w += otherVector.w;
  2995. return this;
  2996. };
  2997. /**
  2998. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2999. */
  3000. Vector4.prototype.add = function (otherVector) {
  3001. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3002. };
  3003. /**
  3004. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3005. * Returns the current Vector4.
  3006. */
  3007. Vector4.prototype.addToRef = function (otherVector, result) {
  3008. result.x = this.x + otherVector.x;
  3009. result.y = this.y + otherVector.y;
  3010. result.z = this.z + otherVector.z;
  3011. result.w = this.w + otherVector.w;
  3012. return this;
  3013. };
  3014. /**
  3015. * Subtract in place the passed vector from the current Vector4.
  3016. * Returns the updated Vector4.
  3017. */
  3018. Vector4.prototype.subtractInPlace = function (otherVector) {
  3019. this.x -= otherVector.x;
  3020. this.y -= otherVector.y;
  3021. this.z -= otherVector.z;
  3022. this.w -= otherVector.w;
  3023. return this;
  3024. };
  3025. /**
  3026. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3027. */
  3028. Vector4.prototype.subtract = function (otherVector) {
  3029. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3030. };
  3031. /**
  3032. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3033. * Returns the current Vector4.
  3034. */
  3035. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3036. result.x = this.x - otherVector.x;
  3037. result.y = this.y - otherVector.y;
  3038. result.z = this.z - otherVector.z;
  3039. result.w = this.w - otherVector.w;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3044. */
  3045. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3046. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3047. };
  3048. /**
  3049. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3050. * Returns the current Vector4.
  3051. */
  3052. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3053. result.x = this.x - x;
  3054. result.y = this.y - y;
  3055. result.z = this.z - z;
  3056. result.w = this.w - w;
  3057. return this;
  3058. };
  3059. /**
  3060. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3061. */
  3062. Vector4.prototype.negate = function () {
  3063. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3064. };
  3065. /**
  3066. * Multiplies the current Vector4 coordinates by scale (float).
  3067. * Returns the updated Vector4.
  3068. */
  3069. Vector4.prototype.scaleInPlace = function (scale) {
  3070. this.x *= scale;
  3071. this.y *= scale;
  3072. this.z *= scale;
  3073. this.w *= scale;
  3074. return this;
  3075. };
  3076. /**
  3077. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3078. */
  3079. Vector4.prototype.scale = function (scale) {
  3080. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3081. };
  3082. /**
  3083. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3084. * Returns the current Vector4.
  3085. */
  3086. Vector4.prototype.scaleToRef = function (scale, result) {
  3087. result.x = this.x * scale;
  3088. result.y = this.y * scale;
  3089. result.z = this.z * scale;
  3090. result.w = this.w * scale;
  3091. return this;
  3092. };
  3093. /**
  3094. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3095. */
  3096. Vector4.prototype.equals = function (otherVector) {
  3097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3098. };
  3099. /**
  3100. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3101. */
  3102. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3103. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3104. return otherVector
  3105. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3106. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3107. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3108. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3109. };
  3110. /**
  3111. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3112. */
  3113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3114. return this.x === x && this.y === y && this.z === z && this.w === w;
  3115. };
  3116. /**
  3117. * Multiplies in place the current Vector4 by the passed one.
  3118. * Returns the updated Vector4.
  3119. */
  3120. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3121. this.x *= otherVector.x;
  3122. this.y *= otherVector.y;
  3123. this.z *= otherVector.z;
  3124. this.w *= otherVector.w;
  3125. return this;
  3126. };
  3127. /**
  3128. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3129. */
  3130. Vector4.prototype.multiply = function (otherVector) {
  3131. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3132. };
  3133. /**
  3134. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3135. * Returns the current Vector4.
  3136. */
  3137. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3138. result.x = this.x * otherVector.x;
  3139. result.y = this.y * otherVector.y;
  3140. result.z = this.z * otherVector.z;
  3141. result.w = this.w * otherVector.w;
  3142. return this;
  3143. };
  3144. /**
  3145. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3146. */
  3147. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3148. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3149. };
  3150. /**
  3151. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3152. */
  3153. Vector4.prototype.divide = function (otherVector) {
  3154. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3155. };
  3156. /**
  3157. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3158. * Returns the current Vector4.
  3159. */
  3160. Vector4.prototype.divideToRef = function (otherVector, result) {
  3161. result.x = this.x / otherVector.x;
  3162. result.y = this.y / otherVector.y;
  3163. result.z = this.z / otherVector.z;
  3164. result.w = this.w / otherVector.w;
  3165. return this;
  3166. };
  3167. /**
  3168. * Divides the current Vector3 coordinates by the passed ones.
  3169. * Returns the updated Vector3.
  3170. */
  3171. Vector4.prototype.divideInPlace = function (otherVector) {
  3172. return this.divideToRef(otherVector, this);
  3173. };
  3174. /**
  3175. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3176. */
  3177. Vector4.prototype.MinimizeInPlace = function (other) {
  3178. if (other.x < this.x)
  3179. this.x = other.x;
  3180. if (other.y < this.y)
  3181. this.y = other.y;
  3182. if (other.z < this.z)
  3183. this.z = other.z;
  3184. if (other.w < this.w)
  3185. this.w = other.w;
  3186. return this;
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MaximizeInPlace = function (other) {
  3192. if (other.x > this.x)
  3193. this.x = other.x;
  3194. if (other.y > this.y)
  3195. this.y = other.y;
  3196. if (other.z > this.z)
  3197. this.z = other.z;
  3198. if (other.w > this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. // Properties
  3203. /**
  3204. * Returns the Vector4 length (float).
  3205. */
  3206. Vector4.prototype.length = function () {
  3207. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3208. };
  3209. /**
  3210. * Returns the Vector4 squared length (float).
  3211. */
  3212. Vector4.prototype.lengthSquared = function () {
  3213. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3214. };
  3215. // Methods
  3216. /**
  3217. * Normalizes in place the Vector4.
  3218. * Returns the updated Vector4.
  3219. */
  3220. Vector4.prototype.normalize = function () {
  3221. var len = this.length();
  3222. if (len === 0)
  3223. return this;
  3224. var num = 1.0 / len;
  3225. this.x *= num;
  3226. this.y *= num;
  3227. this.z *= num;
  3228. this.w *= num;
  3229. return this;
  3230. };
  3231. /**
  3232. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3233. */
  3234. Vector4.prototype.toVector3 = function () {
  3235. return new Vector3(this.x, this.y, this.z);
  3236. };
  3237. /**
  3238. * Returns a new Vector4 copied from the current one.
  3239. */
  3240. Vector4.prototype.clone = function () {
  3241. return new Vector4(this.x, this.y, this.z, this.w);
  3242. };
  3243. /**
  3244. * Updates the current Vector4 with the passed one coordinates.
  3245. * Returns the updated Vector4.
  3246. */
  3247. Vector4.prototype.copyFrom = function (source) {
  3248. this.x = source.x;
  3249. this.y = source.y;
  3250. this.z = source.z;
  3251. this.w = source.w;
  3252. return this;
  3253. };
  3254. /**
  3255. * Updates the current Vector4 coordinates with the passed floats.
  3256. * Returns the updated Vector4.
  3257. */
  3258. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3259. this.x = x;
  3260. this.y = y;
  3261. this.z = z;
  3262. this.w = w;
  3263. return this;
  3264. };
  3265. /**
  3266. * Updates the current Vector4 coordinates with the passed floats.
  3267. * Returns the updated Vector4.
  3268. */
  3269. Vector4.prototype.set = function (x, y, z, w) {
  3270. return this.copyFromFloats(x, y, z, w);
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Vector4 set from the starting index of the passed array.
  3275. */
  3276. Vector4.FromArray = function (array, offset) {
  3277. if (!offset) {
  3278. offset = 0;
  3279. }
  3280. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3281. };
  3282. /**
  3283. * Updates the passed vector "result" from the starting index of the passed array.
  3284. */
  3285. Vector4.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. result.w = array[offset + 3];
  3290. };
  3291. /**
  3292. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3293. */
  3294. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3295. Vector4.FromArrayToRef(array, offset, result);
  3296. };
  3297. /**
  3298. * Updates the passed vector "result" coordinates from the passed floats.
  3299. */
  3300. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. result.w = w;
  3305. };
  3306. /**
  3307. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3308. */
  3309. Vector4.Zero = function () {
  3310. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3314. */
  3315. Vector4.One = function () {
  3316. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3317. };
  3318. /**
  3319. * Returns a new normalized Vector4 from the passed one.
  3320. */
  3321. Vector4.Normalize = function (vector) {
  3322. var result = Vector4.Zero();
  3323. Vector4.NormalizeToRef(vector, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Updates the passed vector "result" from the normalization of the passed one.
  3328. */
  3329. Vector4.NormalizeToRef = function (vector, result) {
  3330. result.copyFrom(vector);
  3331. result.normalize();
  3332. };
  3333. Vector4.Minimize = function (left, right) {
  3334. var min = left.clone();
  3335. min.MinimizeInPlace(right);
  3336. return min;
  3337. };
  3338. Vector4.Maximize = function (left, right) {
  3339. var max = left.clone();
  3340. max.MaximizeInPlace(right);
  3341. return max;
  3342. };
  3343. /**
  3344. * Returns the distance (float) between the vectors "value1" and "value2".
  3345. */
  3346. Vector4.Distance = function (value1, value2) {
  3347. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3348. };
  3349. /**
  3350. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3351. */
  3352. Vector4.DistanceSquared = function (value1, value2) {
  3353. var x = value1.x - value2.x;
  3354. var y = value1.y - value2.y;
  3355. var z = value1.z - value2.z;
  3356. var w = value1.w - value2.w;
  3357. return (x * x) + (y * y) + (z * z) + (w * w);
  3358. };
  3359. /**
  3360. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3361. */
  3362. Vector4.Center = function (value1, value2) {
  3363. var center = value1.add(value2);
  3364. center.scaleInPlace(0.5);
  3365. return center;
  3366. };
  3367. /**
  3368. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3369. * This methods computes transformed normalized direction vectors only.
  3370. */
  3371. Vector4.TransformNormal = function (vector, transformation) {
  3372. var result = Vector4.Zero();
  3373. Vector4.TransformNormalToRef(vector, transformation, result);
  3374. return result;
  3375. };
  3376. /**
  3377. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3378. * This methods computes transformed normalized direction vectors only.
  3379. */
  3380. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3381. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3382. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3383. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3384. result.x = x;
  3385. result.y = y;
  3386. result.z = z;
  3387. result.w = vector.w;
  3388. };
  3389. /**
  3390. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3391. * This methods computes transformed normalized direction vectors only.
  3392. */
  3393. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3394. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3395. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3396. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3397. result.w = w;
  3398. };
  3399. return Vector4;
  3400. }());
  3401. BABYLON.Vector4 = Vector4;
  3402. var Size = /** @class */ (function () {
  3403. /**
  3404. * Creates a Size object from the passed width and height (floats).
  3405. */
  3406. function Size(width, height) {
  3407. this.width = width;
  3408. this.height = height;
  3409. }
  3410. // Returns a string with the Size width and height.
  3411. Size.prototype.toString = function () {
  3412. return "{W: " + this.width + ", H: " + this.height + "}";
  3413. };
  3414. /**
  3415. * Returns the string "Size"
  3416. */
  3417. Size.prototype.getClassName = function () {
  3418. return "Size";
  3419. };
  3420. /**
  3421. * Returns the Size hash code.
  3422. */
  3423. Size.prototype.getHashCode = function () {
  3424. var hash = this.width || 0;
  3425. hash = (hash * 397) ^ (this.height || 0);
  3426. return hash;
  3427. };
  3428. /**
  3429. * Updates the current size from the passed one.
  3430. * Returns the updated Size.
  3431. */
  3432. Size.prototype.copyFrom = function (src) {
  3433. this.width = src.width;
  3434. this.height = src.height;
  3435. };
  3436. /**
  3437. * Updates in place the current Size from the passed floats.
  3438. * Returns the updated Size.
  3439. */
  3440. Size.prototype.copyFromFloats = function (width, height) {
  3441. this.width = width;
  3442. this.height = height;
  3443. return this;
  3444. };
  3445. /**
  3446. * Updates in place the current Size from the passed floats.
  3447. * Returns the updated Size.
  3448. */
  3449. Size.prototype.set = function (width, height) {
  3450. return this.copyFromFloats(width, height);
  3451. };
  3452. /**
  3453. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3454. */
  3455. Size.prototype.multiplyByFloats = function (w, h) {
  3456. return new Size(this.width * w, this.height * h);
  3457. };
  3458. /**
  3459. * Returns a new Size copied from the passed one.
  3460. */
  3461. Size.prototype.clone = function () {
  3462. return new Size(this.width, this.height);
  3463. };
  3464. /**
  3465. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3466. */
  3467. Size.prototype.equals = function (other) {
  3468. if (!other) {
  3469. return false;
  3470. }
  3471. return (this.width === other.width) && (this.height === other.height);
  3472. };
  3473. Object.defineProperty(Size.prototype, "surface", {
  3474. /**
  3475. * Returns the surface of the Size : width * height (float).
  3476. */
  3477. get: function () {
  3478. return this.width * this.height;
  3479. },
  3480. enumerable: true,
  3481. configurable: true
  3482. });
  3483. /**
  3484. * Returns a new Size set to (0.0, 0.0)
  3485. */
  3486. Size.Zero = function () {
  3487. return new Size(0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Size set as the addition result of the current Size and the passed one.
  3491. */
  3492. Size.prototype.add = function (otherSize) {
  3493. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3494. return r;
  3495. };
  3496. /**
  3497. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3498. */
  3499. Size.prototype.subtract = function (otherSize) {
  3500. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3501. return r;
  3502. };
  3503. /**
  3504. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3505. */
  3506. Size.Lerp = function (start, end, amount) {
  3507. var w = start.width + ((end.width - start.width) * amount);
  3508. var h = start.height + ((end.height - start.height) * amount);
  3509. return new Size(w, h);
  3510. };
  3511. return Size;
  3512. }());
  3513. BABYLON.Size = Size;
  3514. var Quaternion = /** @class */ (function () {
  3515. /**
  3516. * Creates a new Quaternion from the passed floats.
  3517. */
  3518. function Quaternion(x, y, z, w) {
  3519. if (x === void 0) { x = 0.0; }
  3520. if (y === void 0) { y = 0.0; }
  3521. if (z === void 0) { z = 0.0; }
  3522. if (w === void 0) { w = 1.0; }
  3523. this.x = x;
  3524. this.y = y;
  3525. this.z = z;
  3526. this.w = w;
  3527. }
  3528. /**
  3529. * Returns a string with the Quaternion coordinates.
  3530. */
  3531. Quaternion.prototype.toString = function () {
  3532. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3533. };
  3534. /**
  3535. * Returns the string "Quaternion".
  3536. */
  3537. Quaternion.prototype.getClassName = function () {
  3538. return "Quaternion";
  3539. };
  3540. /**
  3541. * Returns the Quaternion hash code.
  3542. */
  3543. Quaternion.prototype.getHashCode = function () {
  3544. var hash = this.x || 0;
  3545. hash = (hash * 397) ^ (this.y || 0);
  3546. hash = (hash * 397) ^ (this.z || 0);
  3547. hash = (hash * 397) ^ (this.w || 0);
  3548. return hash;
  3549. };
  3550. /**
  3551. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3552. */
  3553. Quaternion.prototype.asArray = function () {
  3554. return [this.x, this.y, this.z, this.w];
  3555. };
  3556. /**
  3557. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3558. */
  3559. Quaternion.prototype.equals = function (otherQuaternion) {
  3560. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3561. };
  3562. /**
  3563. * Returns a new Quaternion copied from the current one.
  3564. */
  3565. Quaternion.prototype.clone = function () {
  3566. return new Quaternion(this.x, this.y, this.z, this.w);
  3567. };
  3568. /**
  3569. * Updates the current Quaternion from the passed one coordinates.
  3570. * Returns the updated Quaterion.
  3571. */
  3572. Quaternion.prototype.copyFrom = function (other) {
  3573. this.x = other.x;
  3574. this.y = other.y;
  3575. this.z = other.z;
  3576. this.w = other.w;
  3577. return this;
  3578. };
  3579. /**
  3580. * Updates the current Quaternion from the passed float coordinates.
  3581. * Returns the updated Quaterion.
  3582. */
  3583. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3584. this.x = x;
  3585. this.y = y;
  3586. this.z = z;
  3587. this.w = w;
  3588. return this;
  3589. };
  3590. /**
  3591. * Updates the current Quaternion from the passed float coordinates.
  3592. * Returns the updated Quaterion.
  3593. */
  3594. Quaternion.prototype.set = function (x, y, z, w) {
  3595. return this.copyFromFloats(x, y, z, w);
  3596. };
  3597. /**
  3598. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3599. */
  3600. Quaternion.prototype.add = function (other) {
  3601. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3602. };
  3603. /**
  3604. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3605. */
  3606. Quaternion.prototype.subtract = function (other) {
  3607. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3608. };
  3609. /**
  3610. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3611. */
  3612. Quaternion.prototype.scale = function (value) {
  3613. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3614. };
  3615. /**
  3616. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3617. */
  3618. Quaternion.prototype.multiply = function (q1) {
  3619. var result = new Quaternion(0, 0, 0, 1.0);
  3620. this.multiplyToRef(q1, result);
  3621. return result;
  3622. };
  3623. /**
  3624. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3625. * Returns the current Quaternion.
  3626. */
  3627. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3628. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3629. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3630. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3631. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3632. result.copyFromFloats(x, y, z, w);
  3633. return this;
  3634. };
  3635. /**
  3636. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3637. * Returns the updated Quaternion.
  3638. */
  3639. Quaternion.prototype.multiplyInPlace = function (q1) {
  3640. this.multiplyToRef(q1, this);
  3641. return this;
  3642. };
  3643. /**
  3644. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3645. * Returns the current Quaternion.
  3646. */
  3647. Quaternion.prototype.conjugateToRef = function (ref) {
  3648. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3649. return this;
  3650. };
  3651. /**
  3652. * Conjugates in place the current Quaternion.
  3653. * Returns the updated Quaternion.
  3654. */
  3655. Quaternion.prototype.conjugateInPlace = function () {
  3656. this.x *= -1;
  3657. this.y *= -1;
  3658. this.z *= -1;
  3659. return this;
  3660. };
  3661. /**
  3662. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3663. */
  3664. Quaternion.prototype.conjugate = function () {
  3665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3666. return result;
  3667. };
  3668. /**
  3669. * Returns the Quaternion length (float).
  3670. */
  3671. Quaternion.prototype.length = function () {
  3672. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3673. };
  3674. /**
  3675. * Normalize in place the current Quaternion.
  3676. * Returns the updated Quaternion.
  3677. */
  3678. Quaternion.prototype.normalize = function () {
  3679. var length = 1.0 / this.length();
  3680. this.x *= length;
  3681. this.y *= length;
  3682. this.z *= length;
  3683. this.w *= length;
  3684. return this;
  3685. };
  3686. /**
  3687. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3688. */
  3689. Quaternion.prototype.toEulerAngles = function (order) {
  3690. if (order === void 0) { order = "YZX"; }
  3691. var result = Vector3.Zero();
  3692. this.toEulerAnglesToRef(result, order);
  3693. return result;
  3694. };
  3695. /**
  3696. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3697. * Returns the current Quaternion.
  3698. */
  3699. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3700. if (order === void 0) { order = "YZX"; }
  3701. var qz = this.z;
  3702. var qx = this.x;
  3703. var qy = this.y;
  3704. var qw = this.w;
  3705. var sqw = qw * qw;
  3706. var sqz = qz * qz;
  3707. var sqx = qx * qx;
  3708. var sqy = qy * qy;
  3709. var zAxisY = qy * qz - qx * qw;
  3710. var limit = .4999999;
  3711. if (zAxisY < -limit) {
  3712. result.y = 2 * Math.atan2(qy, qw);
  3713. result.x = Math.PI / 2;
  3714. result.z = 0;
  3715. }
  3716. else if (zAxisY > limit) {
  3717. result.y = 2 * Math.atan2(qy, qw);
  3718. result.x = -Math.PI / 2;
  3719. result.z = 0;
  3720. }
  3721. else {
  3722. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3723. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3724. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3725. }
  3726. return this;
  3727. };
  3728. /**
  3729. * Updates the passed rotation matrix with the current Quaternion values.
  3730. * Returns the current Quaternion.
  3731. */
  3732. Quaternion.prototype.toRotationMatrix = function (result) {
  3733. var xx = this.x * this.x;
  3734. var yy = this.y * this.y;
  3735. var zz = this.z * this.z;
  3736. var xy = this.x * this.y;
  3737. var zw = this.z * this.w;
  3738. var zx = this.z * this.x;
  3739. var yw = this.y * this.w;
  3740. var yz = this.y * this.z;
  3741. var xw = this.x * this.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0;
  3754. result.m[12] = 0;
  3755. result.m[13] = 0;
  3756. result.m[14] = 0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. return this;
  3760. };
  3761. /**
  3762. * Updates the current Quaternion from the passed rotation matrix values.
  3763. * Returns the updated Quaternion.
  3764. */
  3765. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3766. Quaternion.FromRotationMatrixToRef(matrix, this);
  3767. return this;
  3768. };
  3769. // Statics
  3770. /**
  3771. * Returns a new Quaternion set from the passed rotation matrix values.
  3772. */
  3773. Quaternion.FromRotationMatrix = function (matrix) {
  3774. var result = new Quaternion();
  3775. Quaternion.FromRotationMatrixToRef(matrix, result);
  3776. return result;
  3777. };
  3778. /**
  3779. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3780. */
  3781. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3782. var data = matrix.m;
  3783. var m11 = data[0], m12 = data[4], m13 = data[8];
  3784. var m21 = data[1], m22 = data[5], m23 = data[9];
  3785. var m31 = data[2], m32 = data[6], m33 = data[10];
  3786. var trace = m11 + m22 + m33;
  3787. var s;
  3788. if (trace > 0) {
  3789. s = 0.5 / Math.sqrt(trace + 1.0);
  3790. result.w = 0.25 / s;
  3791. result.x = (m32 - m23) * s;
  3792. result.y = (m13 - m31) * s;
  3793. result.z = (m21 - m12) * s;
  3794. }
  3795. else if (m11 > m22 && m11 > m33) {
  3796. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3797. result.w = (m32 - m23) / s;
  3798. result.x = 0.25 * s;
  3799. result.y = (m12 + m21) / s;
  3800. result.z = (m13 + m31) / s;
  3801. }
  3802. else if (m22 > m33) {
  3803. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3804. result.w = (m13 - m31) / s;
  3805. result.x = (m12 + m21) / s;
  3806. result.y = 0.25 * s;
  3807. result.z = (m23 + m32) / s;
  3808. }
  3809. else {
  3810. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3811. result.w = (m21 - m12) / s;
  3812. result.x = (m13 + m31) / s;
  3813. result.y = (m23 + m32) / s;
  3814. result.z = 0.25 * s;
  3815. }
  3816. };
  3817. /**
  3818. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3819. */
  3820. Quaternion.Zero = function () {
  3821. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3822. };
  3823. /**
  3824. * Returns a new Quaternion as the inverted current Quaternion.
  3825. */
  3826. Quaternion.Inverse = function (q) {
  3827. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3828. };
  3829. /**
  3830. * Returns the identity Quaternion.
  3831. */
  3832. Quaternion.Identity = function () {
  3833. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3834. };
  3835. Quaternion.IsIdentity = function (quaternion) {
  3836. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3837. };
  3838. /**
  3839. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3840. */
  3841. Quaternion.RotationAxis = function (axis, angle) {
  3842. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3843. };
  3844. /**
  3845. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3846. */
  3847. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3848. var sin = Math.sin(angle / 2);
  3849. axis.normalize();
  3850. result.w = Math.cos(angle / 2);
  3851. result.x = axis.x * sin;
  3852. result.y = axis.y * sin;
  3853. result.z = axis.z * sin;
  3854. return result;
  3855. };
  3856. /**
  3857. * Retuns a new Quaternion set from the starting index of the passed array.
  3858. */
  3859. Quaternion.FromArray = function (array, offset) {
  3860. if (!offset) {
  3861. offset = 0;
  3862. }
  3863. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3864. };
  3865. /**
  3866. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3867. */
  3868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3869. var q = new Quaternion();
  3870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3871. return q;
  3872. };
  3873. /**
  3874. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3875. */
  3876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3878. var halfRoll = roll * 0.5;
  3879. var halfPitch = pitch * 0.5;
  3880. var halfYaw = yaw * 0.5;
  3881. var sinRoll = Math.sin(halfRoll);
  3882. var cosRoll = Math.cos(halfRoll);
  3883. var sinPitch = Math.sin(halfPitch);
  3884. var cosPitch = Math.cos(halfPitch);
  3885. var sinYaw = Math.sin(halfYaw);
  3886. var cosYaw = Math.cos(halfYaw);
  3887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3891. };
  3892. /**
  3893. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3894. */
  3895. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3896. var result = new Quaternion();
  3897. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3898. return result;
  3899. };
  3900. /**
  3901. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3902. */
  3903. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3904. // Produces a quaternion from Euler angles in the z-x-z orientation
  3905. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3906. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3907. var halfBeta = beta * 0.5;
  3908. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3909. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3910. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3911. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3912. };
  3913. /**
  3914. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3915. * cf to Vector3.RotationFromAxis() documentation.
  3916. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3917. */
  3918. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3919. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3920. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3921. return quat;
  3922. };
  3923. /**
  3924. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3925. * cf to Vector3.RotationFromAxis() documentation.
  3926. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3927. */
  3928. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3929. var rotMat = MathTmp.Matrix[0];
  3930. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3931. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3932. };
  3933. Quaternion.Slerp = function (left, right, amount) {
  3934. var result = Quaternion.Identity();
  3935. Quaternion.SlerpToRef(left, right, amount, result);
  3936. return result;
  3937. };
  3938. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3939. var num2;
  3940. var num3;
  3941. var num = amount;
  3942. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3943. var flag = false;
  3944. if (num4 < 0) {
  3945. flag = true;
  3946. num4 = -num4;
  3947. }
  3948. if (num4 > 0.999999) {
  3949. num3 = 1 - num;
  3950. num2 = flag ? -num : num;
  3951. }
  3952. else {
  3953. var num5 = Math.acos(num4);
  3954. var num6 = (1.0 / Math.sin(num5));
  3955. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3956. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3957. }
  3958. result.x = (num3 * left.x) + (num2 * right.x);
  3959. result.y = (num3 * left.y) + (num2 * right.y);
  3960. result.z = (num3 * left.z) + (num2 * right.z);
  3961. result.w = (num3 * left.w) + (num2 * right.w);
  3962. };
  3963. /**
  3964. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3965. */
  3966. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3967. var squared = amount * amount;
  3968. var cubed = amount * squared;
  3969. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3970. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3971. var part3 = (cubed - (2.0 * squared)) + amount;
  3972. var part4 = cubed - squared;
  3973. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3974. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3975. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3976. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3977. return new Quaternion(x, y, z, w);
  3978. };
  3979. return Quaternion;
  3980. }());
  3981. BABYLON.Quaternion = Quaternion;
  3982. var Matrix = /** @class */ (function () {
  3983. function Matrix() {
  3984. this._isIdentity = false;
  3985. this._isIdentityDirty = true;
  3986. this.m = new Float32Array(16);
  3987. this._markAsUpdated();
  3988. }
  3989. Matrix.prototype._markAsUpdated = function () {
  3990. this.updateFlag = Matrix._updateFlagSeed++;
  3991. this._isIdentityDirty = true;
  3992. };
  3993. // Properties
  3994. /**
  3995. * Boolean : True is the matrix is the identity matrix
  3996. */
  3997. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3998. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3999. if (this._isIdentityDirty) {
  4000. this._isIdentityDirty = false;
  4001. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4002. this._isIdentity = false;
  4003. }
  4004. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4005. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4006. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4007. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4008. this._isIdentity = false;
  4009. }
  4010. else {
  4011. this._isIdentity = true;
  4012. }
  4013. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4014. this._isIdentity = false;
  4015. }
  4016. }
  4017. return this._isIdentity;
  4018. };
  4019. /**
  4020. * Returns the matrix determinant (float).
  4021. */
  4022. Matrix.prototype.determinant = function () {
  4023. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4024. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4025. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4026. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4027. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4028. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4029. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4030. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4031. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4032. };
  4033. // Methods
  4034. /**
  4035. * Returns the matrix underlying array.
  4036. */
  4037. Matrix.prototype.toArray = function () {
  4038. return this.m;
  4039. };
  4040. /**
  4041. * Returns the matrix underlying array.
  4042. */
  4043. Matrix.prototype.asArray = function () {
  4044. return this.toArray();
  4045. };
  4046. /**
  4047. * Inverts in place the Matrix.
  4048. * Returns the Matrix inverted.
  4049. */
  4050. Matrix.prototype.invert = function () {
  4051. this.invertToRef(this);
  4052. return this;
  4053. };
  4054. /**
  4055. * Sets all the matrix elements to zero.
  4056. * Returns the Matrix.
  4057. */
  4058. Matrix.prototype.reset = function () {
  4059. for (var index = 0; index < 16; index++) {
  4060. this.m[index] = 0.0;
  4061. }
  4062. this._markAsUpdated();
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4067. */
  4068. Matrix.prototype.add = function (other) {
  4069. var result = new Matrix();
  4070. this.addToRef(other, result);
  4071. return result;
  4072. };
  4073. /**
  4074. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4075. * Returns the Matrix.
  4076. */
  4077. Matrix.prototype.addToRef = function (other, result) {
  4078. for (var index = 0; index < 16; index++) {
  4079. result.m[index] = this.m[index] + other.m[index];
  4080. }
  4081. result._markAsUpdated();
  4082. return this;
  4083. };
  4084. /**
  4085. * Adds in place the passed matrix to the current Matrix.
  4086. * Returns the updated Matrix.
  4087. */
  4088. Matrix.prototype.addToSelf = function (other) {
  4089. for (var index = 0; index < 16; index++) {
  4090. this.m[index] += other.m[index];
  4091. }
  4092. this._markAsUpdated();
  4093. return this;
  4094. };
  4095. /**
  4096. * Sets the passed matrix with the current inverted Matrix.
  4097. * Returns the unmodified current Matrix.
  4098. */
  4099. Matrix.prototype.invertToRef = function (other) {
  4100. var l1 = this.m[0];
  4101. var l2 = this.m[1];
  4102. var l3 = this.m[2];
  4103. var l4 = this.m[3];
  4104. var l5 = this.m[4];
  4105. var l6 = this.m[5];
  4106. var l7 = this.m[6];
  4107. var l8 = this.m[7];
  4108. var l9 = this.m[8];
  4109. var l10 = this.m[9];
  4110. var l11 = this.m[10];
  4111. var l12 = this.m[11];
  4112. var l13 = this.m[12];
  4113. var l14 = this.m[13];
  4114. var l15 = this.m[14];
  4115. var l16 = this.m[15];
  4116. var l17 = (l11 * l16) - (l12 * l15);
  4117. var l18 = (l10 * l16) - (l12 * l14);
  4118. var l19 = (l10 * l15) - (l11 * l14);
  4119. var l20 = (l9 * l16) - (l12 * l13);
  4120. var l21 = (l9 * l15) - (l11 * l13);
  4121. var l22 = (l9 * l14) - (l10 * l13);
  4122. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4123. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4124. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4125. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4126. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4127. var l28 = (l7 * l16) - (l8 * l15);
  4128. var l29 = (l6 * l16) - (l8 * l14);
  4129. var l30 = (l6 * l15) - (l7 * l14);
  4130. var l31 = (l5 * l16) - (l8 * l13);
  4131. var l32 = (l5 * l15) - (l7 * l13);
  4132. var l33 = (l5 * l14) - (l6 * l13);
  4133. var l34 = (l7 * l12) - (l8 * l11);
  4134. var l35 = (l6 * l12) - (l8 * l10);
  4135. var l36 = (l6 * l11) - (l7 * l10);
  4136. var l37 = (l5 * l12) - (l8 * l9);
  4137. var l38 = (l5 * l11) - (l7 * l9);
  4138. var l39 = (l5 * l10) - (l6 * l9);
  4139. other.m[0] = l23 * l27;
  4140. other.m[4] = l24 * l27;
  4141. other.m[8] = l25 * l27;
  4142. other.m[12] = l26 * l27;
  4143. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4144. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4145. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4146. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4147. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4148. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4149. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4150. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4151. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4152. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4153. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4154. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4155. other._markAsUpdated();
  4156. return this;
  4157. };
  4158. /**
  4159. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4160. * Returns the updated Matrix.
  4161. */
  4162. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4163. this.m[12] = x;
  4164. this.m[13] = y;
  4165. this.m[14] = z;
  4166. this._markAsUpdated();
  4167. return this;
  4168. };
  4169. /**
  4170. * Inserts the translation vector in the current Matrix.
  4171. * Returns the updated Matrix.
  4172. */
  4173. Matrix.prototype.setTranslation = function (vector3) {
  4174. this.m[12] = vector3.x;
  4175. this.m[13] = vector3.y;
  4176. this.m[14] = vector3.z;
  4177. this._markAsUpdated();
  4178. return this;
  4179. };
  4180. /**
  4181. * Returns a new Vector3 as the extracted translation from the Matrix.
  4182. */
  4183. Matrix.prototype.getTranslation = function () {
  4184. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4185. };
  4186. /**
  4187. * Fill a Vector3 with the extracted translation from the Matrix.
  4188. */
  4189. Matrix.prototype.getTranslationToRef = function (result) {
  4190. result.x = this.m[12];
  4191. result.y = this.m[13];
  4192. result.z = this.m[14];
  4193. return this;
  4194. };
  4195. /**
  4196. * Remove rotation and scaling part from the Matrix.
  4197. * Returns the updated Matrix.
  4198. */
  4199. Matrix.prototype.removeRotationAndScaling = function () {
  4200. this.setRowFromFloats(0, 1, 0, 0, 0);
  4201. this.setRowFromFloats(1, 0, 1, 0, 0);
  4202. this.setRowFromFloats(2, 0, 0, 1, 0);
  4203. return this;
  4204. };
  4205. /**
  4206. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4207. */
  4208. Matrix.prototype.multiply = function (other) {
  4209. var result = new Matrix();
  4210. this.multiplyToRef(other, result);
  4211. return result;
  4212. };
  4213. /**
  4214. * Updates the current Matrix from the passed one values.
  4215. * Returns the updated Matrix.
  4216. */
  4217. Matrix.prototype.copyFrom = function (other) {
  4218. for (var index = 0; index < 16; index++) {
  4219. this.m[index] = other.m[index];
  4220. }
  4221. this._markAsUpdated();
  4222. return this;
  4223. };
  4224. /**
  4225. * Populates the passed array from the starting index with the Matrix values.
  4226. * Returns the Matrix.
  4227. */
  4228. Matrix.prototype.copyToArray = function (array, offset) {
  4229. if (offset === void 0) { offset = 0; }
  4230. for (var index = 0; index < 16; index++) {
  4231. array[offset + index] = this.m[index];
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4237. */
  4238. Matrix.prototype.multiplyToRef = function (other, result) {
  4239. this.multiplyToArray(other, result.m, 0);
  4240. result._markAsUpdated();
  4241. return this;
  4242. };
  4243. /**
  4244. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4245. */
  4246. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4247. var tm0 = this.m[0];
  4248. var tm1 = this.m[1];
  4249. var tm2 = this.m[2];
  4250. var tm3 = this.m[3];
  4251. var tm4 = this.m[4];
  4252. var tm5 = this.m[5];
  4253. var tm6 = this.m[6];
  4254. var tm7 = this.m[7];
  4255. var tm8 = this.m[8];
  4256. var tm9 = this.m[9];
  4257. var tm10 = this.m[10];
  4258. var tm11 = this.m[11];
  4259. var tm12 = this.m[12];
  4260. var tm13 = this.m[13];
  4261. var tm14 = this.m[14];
  4262. var tm15 = this.m[15];
  4263. var om0 = other.m[0];
  4264. var om1 = other.m[1];
  4265. var om2 = other.m[2];
  4266. var om3 = other.m[3];
  4267. var om4 = other.m[4];
  4268. var om5 = other.m[5];
  4269. var om6 = other.m[6];
  4270. var om7 = other.m[7];
  4271. var om8 = other.m[8];
  4272. var om9 = other.m[9];
  4273. var om10 = other.m[10];
  4274. var om11 = other.m[11];
  4275. var om12 = other.m[12];
  4276. var om13 = other.m[13];
  4277. var om14 = other.m[14];
  4278. var om15 = other.m[15];
  4279. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4280. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4281. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4282. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4283. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4284. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4285. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4286. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4287. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4288. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4289. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4290. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4291. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4292. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4293. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4294. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4295. return this;
  4296. };
  4297. /**
  4298. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4299. */
  4300. Matrix.prototype.equals = function (value) {
  4301. return value &&
  4302. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4303. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4304. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4305. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4306. };
  4307. /**
  4308. * Returns a new Matrix from the current Matrix.
  4309. */
  4310. Matrix.prototype.clone = function () {
  4311. 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]);
  4312. };
  4313. /**
  4314. * Returns the string "Matrix"
  4315. */
  4316. Matrix.prototype.getClassName = function () {
  4317. return "Matrix";
  4318. };
  4319. /**
  4320. * Returns the Matrix hash code.
  4321. */
  4322. Matrix.prototype.getHashCode = function () {
  4323. var hash = this.m[0] || 0;
  4324. for (var i = 1; i < 16; i++) {
  4325. hash = (hash * 397) ^ (this.m[i] || 0);
  4326. }
  4327. return hash;
  4328. };
  4329. /**
  4330. * Decomposes the current Matrix into :
  4331. * - a scale vector3 passed as a reference to update,
  4332. * - a rotation quaternion passed as a reference to update,
  4333. * - a translation vector3 passed as a reference to update.
  4334. * Returns the true if operation was successful.
  4335. */
  4336. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4337. translation.x = this.m[12];
  4338. translation.y = this.m[13];
  4339. translation.z = this.m[14];
  4340. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4341. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4342. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4343. if (this.determinant() <= 0) {
  4344. scale.y *= -1;
  4345. }
  4346. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4347. rotation.x = 0;
  4348. rotation.y = 0;
  4349. rotation.z = 0;
  4350. rotation.w = 1;
  4351. return false;
  4352. }
  4353. 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]);
  4354. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4355. return true;
  4356. };
  4357. /**
  4358. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4359. */
  4360. Matrix.prototype.getRotationMatrix = function () {
  4361. var result = Matrix.Identity();
  4362. this.getRotationMatrixToRef(result);
  4363. return result;
  4364. };
  4365. /**
  4366. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4367. * Returns the current Matrix.
  4368. */
  4369. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4370. var m = this.m;
  4371. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4372. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4373. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4374. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4375. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4376. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4377. 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);
  4378. return this;
  4379. };
  4380. // Statics
  4381. /**
  4382. * Returns a new Matrix set from the starting index of the passed array.
  4383. */
  4384. Matrix.FromArray = function (array, offset) {
  4385. var result = new Matrix();
  4386. if (!offset) {
  4387. offset = 0;
  4388. }
  4389. Matrix.FromArrayToRef(array, offset, result);
  4390. return result;
  4391. };
  4392. /**
  4393. * Sets the passed "result" matrix from the starting index of the passed array.
  4394. */
  4395. Matrix.FromArrayToRef = function (array, offset, result) {
  4396. for (var index = 0; index < 16; index++) {
  4397. result.m[index] = array[index + offset];
  4398. }
  4399. result._markAsUpdated();
  4400. };
  4401. /**
  4402. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4403. */
  4404. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4405. for (var index = 0; index < 16; index++) {
  4406. result.m[index] = array[index + offset] * scale;
  4407. }
  4408. result._markAsUpdated();
  4409. };
  4410. /**
  4411. * Sets the passed matrix "result" with the 16 passed floats.
  4412. */
  4413. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4414. result.m[0] = initialM11;
  4415. result.m[1] = initialM12;
  4416. result.m[2] = initialM13;
  4417. result.m[3] = initialM14;
  4418. result.m[4] = initialM21;
  4419. result.m[5] = initialM22;
  4420. result.m[6] = initialM23;
  4421. result.m[7] = initialM24;
  4422. result.m[8] = initialM31;
  4423. result.m[9] = initialM32;
  4424. result.m[10] = initialM33;
  4425. result.m[11] = initialM34;
  4426. result.m[12] = initialM41;
  4427. result.m[13] = initialM42;
  4428. result.m[14] = initialM43;
  4429. result.m[15] = initialM44;
  4430. result._markAsUpdated();
  4431. };
  4432. /**
  4433. * Returns the index-th row of the current matrix as a new Vector4.
  4434. */
  4435. Matrix.prototype.getRow = function (index) {
  4436. if (index < 0 || index > 3) {
  4437. return null;
  4438. }
  4439. var i = index * 4;
  4440. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4441. };
  4442. /**
  4443. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4444. * Returns the updated Matrix.
  4445. */
  4446. Matrix.prototype.setRow = function (index, row) {
  4447. if (index < 0 || index > 3) {
  4448. return this;
  4449. }
  4450. var i = index * 4;
  4451. this.m[i + 0] = row.x;
  4452. this.m[i + 1] = row.y;
  4453. this.m[i + 2] = row.z;
  4454. this.m[i + 3] = row.w;
  4455. this._markAsUpdated();
  4456. return this;
  4457. };
  4458. /**
  4459. * Compute the transpose of the matrix.
  4460. * Returns a new Matrix.
  4461. */
  4462. Matrix.prototype.transpose = function () {
  4463. return Matrix.Transpose(this);
  4464. };
  4465. /**
  4466. * Compute the transpose of the matrix.
  4467. * Returns the current matrix.
  4468. */
  4469. Matrix.prototype.transposeToRef = function (result) {
  4470. Matrix.TransposeToRef(this, result);
  4471. return this;
  4472. };
  4473. /**
  4474. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4475. * Returns the updated Matrix.
  4476. */
  4477. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4478. if (index < 0 || index > 3) {
  4479. return this;
  4480. }
  4481. var i = index * 4;
  4482. this.m[i + 0] = x;
  4483. this.m[i + 1] = y;
  4484. this.m[i + 2] = z;
  4485. this.m[i + 3] = w;
  4486. this._markAsUpdated();
  4487. return this;
  4488. };
  4489. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4490. /**
  4491. * Static identity matrix to be used as readonly matrix
  4492. * Must not be updated.
  4493. */
  4494. get: function () {
  4495. return Matrix._identityReadOnly;
  4496. },
  4497. enumerable: true,
  4498. configurable: true
  4499. });
  4500. /**
  4501. * Returns a new Matrix set from the 16 passed floats.
  4502. */
  4503. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4504. var result = new Matrix();
  4505. result.m[0] = initialM11;
  4506. result.m[1] = initialM12;
  4507. result.m[2] = initialM13;
  4508. result.m[3] = initialM14;
  4509. result.m[4] = initialM21;
  4510. result.m[5] = initialM22;
  4511. result.m[6] = initialM23;
  4512. result.m[7] = initialM24;
  4513. result.m[8] = initialM31;
  4514. result.m[9] = initialM32;
  4515. result.m[10] = initialM33;
  4516. result.m[11] = initialM34;
  4517. result.m[12] = initialM41;
  4518. result.m[13] = initialM42;
  4519. result.m[14] = initialM43;
  4520. result.m[15] = initialM44;
  4521. return result;
  4522. };
  4523. /**
  4524. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4525. */
  4526. Matrix.Compose = function (scale, rotation, translation) {
  4527. var result = Matrix.Identity();
  4528. Matrix.ComposeToRef(scale, rotation, translation, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4533. */
  4534. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4535. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4536. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4537. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4538. result.setTranslation(translation);
  4539. };
  4540. /**
  4541. * Returns a new indentity Matrix.
  4542. */
  4543. Matrix.Identity = function () {
  4544. 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);
  4545. };
  4546. /**
  4547. * Sets the passed "result" as an identity matrix.
  4548. */
  4549. Matrix.IdentityToRef = function (result) {
  4550. 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);
  4551. };
  4552. /**
  4553. * Returns a new zero Matrix.
  4554. */
  4555. Matrix.Zero = function () {
  4556. 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);
  4557. };
  4558. /**
  4559. * Returns a new rotation matrix for "angle" radians around the X axis.
  4560. */
  4561. Matrix.RotationX = function (angle) {
  4562. var result = new Matrix();
  4563. Matrix.RotationXToRef(angle, result);
  4564. return result;
  4565. };
  4566. /**
  4567. * Returns a new Matrix as the passed inverted one.
  4568. */
  4569. Matrix.Invert = function (source) {
  4570. var result = new Matrix();
  4571. source.invertToRef(result);
  4572. return result;
  4573. };
  4574. /**
  4575. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4576. */
  4577. Matrix.RotationXToRef = function (angle, result) {
  4578. var s = Math.sin(angle);
  4579. var c = Math.cos(angle);
  4580. result.m[0] = 1.0;
  4581. result.m[15] = 1.0;
  4582. result.m[5] = c;
  4583. result.m[10] = c;
  4584. result.m[9] = -s;
  4585. result.m[6] = s;
  4586. result.m[1] = 0.0;
  4587. result.m[2] = 0.0;
  4588. result.m[3] = 0.0;
  4589. result.m[4] = 0.0;
  4590. result.m[7] = 0.0;
  4591. result.m[8] = 0.0;
  4592. result.m[11] = 0.0;
  4593. result.m[12] = 0.0;
  4594. result.m[13] = 0.0;
  4595. result.m[14] = 0.0;
  4596. result._markAsUpdated();
  4597. };
  4598. /**
  4599. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4600. */
  4601. Matrix.RotationY = function (angle) {
  4602. var result = new Matrix();
  4603. Matrix.RotationYToRef(angle, result);
  4604. return result;
  4605. };
  4606. /**
  4607. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4608. */
  4609. Matrix.RotationYToRef = function (angle, result) {
  4610. var s = Math.sin(angle);
  4611. var c = Math.cos(angle);
  4612. result.m[5] = 1.0;
  4613. result.m[15] = 1.0;
  4614. result.m[0] = c;
  4615. result.m[2] = -s;
  4616. result.m[8] = s;
  4617. result.m[10] = c;
  4618. result.m[1] = 0.0;
  4619. result.m[3] = 0.0;
  4620. result.m[4] = 0.0;
  4621. result.m[6] = 0.0;
  4622. result.m[7] = 0.0;
  4623. result.m[9] = 0.0;
  4624. result.m[11] = 0.0;
  4625. result.m[12] = 0.0;
  4626. result.m[13] = 0.0;
  4627. result.m[14] = 0.0;
  4628. result._markAsUpdated();
  4629. };
  4630. /**
  4631. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4632. */
  4633. Matrix.RotationZ = function (angle) {
  4634. var result = new Matrix();
  4635. Matrix.RotationZToRef(angle, result);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4640. */
  4641. Matrix.RotationZToRef = function (angle, result) {
  4642. var s = Math.sin(angle);
  4643. var c = Math.cos(angle);
  4644. result.m[10] = 1.0;
  4645. result.m[15] = 1.0;
  4646. result.m[0] = c;
  4647. result.m[1] = s;
  4648. result.m[4] = -s;
  4649. result.m[5] = c;
  4650. result.m[2] = 0.0;
  4651. result.m[3] = 0.0;
  4652. result.m[6] = 0.0;
  4653. result.m[7] = 0.0;
  4654. result.m[8] = 0.0;
  4655. result.m[9] = 0.0;
  4656. result.m[11] = 0.0;
  4657. result.m[12] = 0.0;
  4658. result.m[13] = 0.0;
  4659. result.m[14] = 0.0;
  4660. result._markAsUpdated();
  4661. };
  4662. /**
  4663. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4664. */
  4665. Matrix.RotationAxis = function (axis, angle) {
  4666. var result = Matrix.Zero();
  4667. Matrix.RotationAxisToRef(axis, angle, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4672. */
  4673. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4674. var s = Math.sin(-angle);
  4675. var c = Math.cos(-angle);
  4676. var c1 = 1 - c;
  4677. axis.normalize();
  4678. result.m[0] = (axis.x * axis.x) * c1 + c;
  4679. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4680. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4681. result.m[3] = 0.0;
  4682. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4683. result.m[5] = (axis.y * axis.y) * c1 + c;
  4684. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4685. result.m[7] = 0.0;
  4686. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4687. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4688. result.m[10] = (axis.z * axis.z) * c1 + c;
  4689. result.m[11] = 0.0;
  4690. result.m[15] = 1.0;
  4691. result._markAsUpdated();
  4692. };
  4693. /**
  4694. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4695. */
  4696. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4697. var result = new Matrix();
  4698. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4699. return result;
  4700. };
  4701. /**
  4702. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4703. */
  4704. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4705. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4706. this._tempQuaternion.toRotationMatrix(result);
  4707. };
  4708. /**
  4709. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4710. */
  4711. Matrix.Scaling = function (x, y, z) {
  4712. var result = Matrix.Zero();
  4713. Matrix.ScalingToRef(x, y, z, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4718. */
  4719. Matrix.ScalingToRef = function (x, y, z, result) {
  4720. result.m[0] = x;
  4721. result.m[1] = 0.0;
  4722. result.m[2] = 0.0;
  4723. result.m[3] = 0.0;
  4724. result.m[4] = 0.0;
  4725. result.m[5] = y;
  4726. result.m[6] = 0.0;
  4727. result.m[7] = 0.0;
  4728. result.m[8] = 0.0;
  4729. result.m[9] = 0.0;
  4730. result.m[10] = z;
  4731. result.m[11] = 0.0;
  4732. result.m[12] = 0.0;
  4733. result.m[13] = 0.0;
  4734. result.m[14] = 0.0;
  4735. result.m[15] = 1.0;
  4736. result._markAsUpdated();
  4737. };
  4738. /**
  4739. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4740. */
  4741. Matrix.Translation = function (x, y, z) {
  4742. var result = Matrix.Identity();
  4743. Matrix.TranslationToRef(x, y, z, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4748. */
  4749. Matrix.TranslationToRef = function (x, y, z, result) {
  4750. 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);
  4751. };
  4752. /**
  4753. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4754. */
  4755. Matrix.Lerp = function (startValue, endValue, gradient) {
  4756. var result = Matrix.Zero();
  4757. for (var index = 0; index < 16; index++) {
  4758. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4759. }
  4760. result._markAsUpdated();
  4761. return result;
  4762. };
  4763. /**
  4764. * Returns a new Matrix whose values are computed by :
  4765. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4766. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4767. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4768. */
  4769. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4770. var startScale = new Vector3(0, 0, 0);
  4771. var startRotation = new Quaternion();
  4772. var startTranslation = new Vector3(0, 0, 0);
  4773. startValue.decompose(startScale, startRotation, startTranslation);
  4774. var endScale = new Vector3(0, 0, 0);
  4775. var endRotation = new Quaternion();
  4776. var endTranslation = new Vector3(0, 0, 0);
  4777. endValue.decompose(endScale, endRotation, endTranslation);
  4778. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4779. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4780. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4781. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4782. };
  4783. /**
  4784. * 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".
  4785. * This methods works for a Left-Handed system.
  4786. */
  4787. Matrix.LookAtLH = function (eye, target, up) {
  4788. var result = Matrix.Zero();
  4789. Matrix.LookAtLHToRef(eye, target, up, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * 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".
  4794. * This methods works for a Left-Handed system.
  4795. */
  4796. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4797. // Z axis
  4798. target.subtractToRef(eye, this._zAxis);
  4799. this._zAxis.normalize();
  4800. // X axis
  4801. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4802. if (this._xAxis.lengthSquared() === 0) {
  4803. this._xAxis.x = 1.0;
  4804. }
  4805. else {
  4806. this._xAxis.normalize();
  4807. }
  4808. // Y axis
  4809. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4810. this._yAxis.normalize();
  4811. // Eye angles
  4812. var ex = -Vector3.Dot(this._xAxis, eye);
  4813. var ey = -Vector3.Dot(this._yAxis, eye);
  4814. var ez = -Vector3.Dot(this._zAxis, eye);
  4815. 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);
  4816. };
  4817. /**
  4818. * 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".
  4819. * This methods works for a Right-Handed system.
  4820. */
  4821. Matrix.LookAtRH = function (eye, target, up) {
  4822. var result = Matrix.Zero();
  4823. Matrix.LookAtRHToRef(eye, target, up, result);
  4824. return result;
  4825. };
  4826. /**
  4827. * 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".
  4828. * This methods works for a Left-Handed system.
  4829. */
  4830. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4831. // Z axis
  4832. eye.subtractToRef(target, this._zAxis);
  4833. this._zAxis.normalize();
  4834. // X axis
  4835. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4836. if (this._xAxis.lengthSquared() === 0) {
  4837. this._xAxis.x = 1.0;
  4838. }
  4839. else {
  4840. this._xAxis.normalize();
  4841. }
  4842. // Y axis
  4843. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4844. this._yAxis.normalize();
  4845. // Eye angles
  4846. var ex = -Vector3.Dot(this._xAxis, eye);
  4847. var ey = -Vector3.Dot(this._yAxis, eye);
  4848. var ez = -Vector3.Dot(this._zAxis, eye);
  4849. 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);
  4850. };
  4851. /**
  4852. * 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.
  4853. */
  4854. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4855. var matrix = Matrix.Zero();
  4856. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4857. return matrix;
  4858. };
  4859. /**
  4860. * 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.
  4861. */
  4862. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4863. var n = znear;
  4864. var f = zfar;
  4865. var a = 2.0 / width;
  4866. var b = 2.0 / height;
  4867. var c = 2.0 / (f - n);
  4868. var d = -(f + n) / (f - n);
  4869. 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);
  4870. };
  4871. /**
  4872. * 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.
  4873. */
  4874. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4875. var matrix = Matrix.Zero();
  4876. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4877. return matrix;
  4878. };
  4879. /**
  4880. * 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.
  4881. */
  4882. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4883. var n = znear;
  4884. var f = zfar;
  4885. var a = 2.0 / (right - left);
  4886. var b = 2.0 / (top - bottom);
  4887. var c = 2.0 / (f - n);
  4888. var d = -(f + n) / (f - n);
  4889. var i0 = (left + right) / (left - right);
  4890. var i1 = (top + bottom) / (bottom - top);
  4891. 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);
  4892. };
  4893. /**
  4894. * 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.
  4895. */
  4896. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4897. var matrix = Matrix.Zero();
  4898. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4899. return matrix;
  4900. };
  4901. /**
  4902. * 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.
  4903. */
  4904. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4905. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4906. result.m[10] *= -1.0;
  4907. };
  4908. /**
  4909. * 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.
  4910. */
  4911. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4912. var matrix = Matrix.Zero();
  4913. var n = znear;
  4914. var f = zfar;
  4915. var a = 2.0 * n / width;
  4916. var b = 2.0 * n / height;
  4917. var c = (f + n) / (f - n);
  4918. var d = -2.0 * f * n / (f - n);
  4919. 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);
  4920. return matrix;
  4921. };
  4922. /**
  4923. * 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.
  4924. */
  4925. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4928. return matrix;
  4929. };
  4930. /**
  4931. * 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.
  4932. */
  4933. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4934. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4935. var n = znear;
  4936. var f = zfar;
  4937. var t = 1.0 / (Math.tan(fov * 0.5));
  4938. var a = isVerticalFovFixed ? (t / aspect) : t;
  4939. var b = isVerticalFovFixed ? t : (t * aspect);
  4940. var c = (f + n) / (f - n);
  4941. var d = -2.0 * f * n / (f - n);
  4942. 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);
  4943. };
  4944. /**
  4945. * 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.
  4946. */
  4947. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4948. var matrix = Matrix.Zero();
  4949. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4950. return matrix;
  4951. };
  4952. /**
  4953. * 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.
  4954. */
  4955. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4956. //alternatively this could be expressed as:
  4957. // m = PerspectiveFovLHToRef
  4958. // m[10] *= -1.0;
  4959. // m[11] *= -1.0;
  4960. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4961. var n = znear;
  4962. var f = zfar;
  4963. var t = 1.0 / (Math.tan(fov * 0.5));
  4964. var a = isVerticalFovFixed ? (t / aspect) : t;
  4965. var b = isVerticalFovFixed ? t : (t * aspect);
  4966. var c = -(f + n) / (f - n);
  4967. var d = -2 * f * n / (f - n);
  4968. 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);
  4969. };
  4970. /**
  4971. * 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.
  4972. */
  4973. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4974. if (rightHanded === void 0) { rightHanded = false; }
  4975. var rightHandedFactor = rightHanded ? -1 : 1;
  4976. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4977. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4978. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4979. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4980. var xScale = 2.0 / (leftTan + rightTan);
  4981. var yScale = 2.0 / (upTan + downTan);
  4982. result.m[0] = xScale;
  4983. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4984. result.m[5] = yScale;
  4985. result.m[6] = result.m[7] = 0.0;
  4986. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4987. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4988. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4989. result.m[10] = -zfar / (znear - zfar);
  4990. result.m[11] = 1.0 * rightHandedFactor;
  4991. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4992. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4993. // result.m[14] = (znear * zfar) / (znear - zfar);
  4994. result._markAsUpdated();
  4995. };
  4996. /**
  4997. * Returns the final transformation matrix : world * view * projection * viewport
  4998. */
  4999. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5000. var cw = viewport.width;
  5001. var ch = viewport.height;
  5002. var cx = viewport.x;
  5003. var cy = viewport.y;
  5004. 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);
  5005. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5006. };
  5007. /**
  5008. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5009. */
  5010. Matrix.GetAsMatrix2x2 = function (matrix) {
  5011. return new Float32Array([
  5012. matrix.m[0], matrix.m[1],
  5013. matrix.m[4], matrix.m[5]
  5014. ]);
  5015. };
  5016. /**
  5017. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5018. */
  5019. Matrix.GetAsMatrix3x3 = function (matrix) {
  5020. return new Float32Array([
  5021. matrix.m[0], matrix.m[1], matrix.m[2],
  5022. matrix.m[4], matrix.m[5], matrix.m[6],
  5023. matrix.m[8], matrix.m[9], matrix.m[10]
  5024. ]);
  5025. };
  5026. /**
  5027. * Compute the transpose of the passed Matrix.
  5028. * Returns a new Matrix.
  5029. */
  5030. Matrix.Transpose = function (matrix) {
  5031. var result = new Matrix();
  5032. Matrix.TransposeToRef(matrix, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5037. */
  5038. Matrix.TransposeToRef = function (matrix, result) {
  5039. result.m[0] = matrix.m[0];
  5040. result.m[1] = matrix.m[4];
  5041. result.m[2] = matrix.m[8];
  5042. result.m[3] = matrix.m[12];
  5043. result.m[4] = matrix.m[1];
  5044. result.m[5] = matrix.m[5];
  5045. result.m[6] = matrix.m[9];
  5046. result.m[7] = matrix.m[13];
  5047. result.m[8] = matrix.m[2];
  5048. result.m[9] = matrix.m[6];
  5049. result.m[10] = matrix.m[10];
  5050. result.m[11] = matrix.m[14];
  5051. result.m[12] = matrix.m[3];
  5052. result.m[13] = matrix.m[7];
  5053. result.m[14] = matrix.m[11];
  5054. result.m[15] = matrix.m[15];
  5055. };
  5056. /**
  5057. * Returns a new Matrix as the reflection matrix across the passed plane.
  5058. */
  5059. Matrix.Reflection = function (plane) {
  5060. var matrix = new Matrix();
  5061. Matrix.ReflectionToRef(plane, matrix);
  5062. return matrix;
  5063. };
  5064. /**
  5065. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5066. */
  5067. Matrix.ReflectionToRef = function (plane, result) {
  5068. plane.normalize();
  5069. var x = plane.normal.x;
  5070. var y = plane.normal.y;
  5071. var z = plane.normal.z;
  5072. var temp = -2 * x;
  5073. var temp2 = -2 * y;
  5074. var temp3 = -2 * z;
  5075. result.m[0] = (temp * x) + 1;
  5076. result.m[1] = temp2 * x;
  5077. result.m[2] = temp3 * x;
  5078. result.m[3] = 0.0;
  5079. result.m[4] = temp * y;
  5080. result.m[5] = (temp2 * y) + 1;
  5081. result.m[6] = temp3 * y;
  5082. result.m[7] = 0.0;
  5083. result.m[8] = temp * z;
  5084. result.m[9] = temp2 * z;
  5085. result.m[10] = (temp3 * z) + 1;
  5086. result.m[11] = 0.0;
  5087. result.m[12] = temp * plane.d;
  5088. result.m[13] = temp2 * plane.d;
  5089. result.m[14] = temp3 * plane.d;
  5090. result.m[15] = 1.0;
  5091. result._markAsUpdated();
  5092. };
  5093. /**
  5094. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5095. */
  5096. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5097. result.m[0] = xaxis.x;
  5098. result.m[1] = xaxis.y;
  5099. result.m[2] = xaxis.z;
  5100. result.m[3] = 0.0;
  5101. result.m[4] = yaxis.x;
  5102. result.m[5] = yaxis.y;
  5103. result.m[6] = yaxis.z;
  5104. result.m[7] = 0.0;
  5105. result.m[8] = zaxis.x;
  5106. result.m[9] = zaxis.y;
  5107. result.m[10] = zaxis.z;
  5108. result.m[11] = 0.0;
  5109. result.m[12] = 0.0;
  5110. result.m[13] = 0.0;
  5111. result.m[14] = 0.0;
  5112. result.m[15] = 1.0;
  5113. result._markAsUpdated();
  5114. };
  5115. /**
  5116. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5117. */
  5118. Matrix.FromQuaternionToRef = function (quat, result) {
  5119. var xx = quat.x * quat.x;
  5120. var yy = quat.y * quat.y;
  5121. var zz = quat.z * quat.z;
  5122. var xy = quat.x * quat.y;
  5123. var zw = quat.z * quat.w;
  5124. var zx = quat.z * quat.x;
  5125. var yw = quat.y * quat.w;
  5126. var yz = quat.y * quat.z;
  5127. var xw = quat.x * quat.w;
  5128. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5129. result.m[1] = 2.0 * (xy + zw);
  5130. result.m[2] = 2.0 * (zx - yw);
  5131. result.m[3] = 0.0;
  5132. result.m[4] = 2.0 * (xy - zw);
  5133. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5134. result.m[6] = 2.0 * (yz + xw);
  5135. result.m[7] = 0.0;
  5136. result.m[8] = 2.0 * (zx + yw);
  5137. result.m[9] = 2.0 * (yz - xw);
  5138. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5139. result.m[11] = 0.0;
  5140. result.m[12] = 0.0;
  5141. result.m[13] = 0.0;
  5142. result.m[14] = 0.0;
  5143. result.m[15] = 1.0;
  5144. result._markAsUpdated();
  5145. };
  5146. Matrix._tempQuaternion = new Quaternion();
  5147. Matrix._xAxis = Vector3.Zero();
  5148. Matrix._yAxis = Vector3.Zero();
  5149. Matrix._zAxis = Vector3.Zero();
  5150. Matrix._updateFlagSeed = 0;
  5151. Matrix._identityReadOnly = Matrix.Identity();
  5152. return Matrix;
  5153. }());
  5154. BABYLON.Matrix = Matrix;
  5155. var Plane = /** @class */ (function () {
  5156. /**
  5157. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5158. */
  5159. function Plane(a, b, c, d) {
  5160. this.normal = new Vector3(a, b, c);
  5161. this.d = d;
  5162. }
  5163. /**
  5164. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5165. */
  5166. Plane.prototype.asArray = function () {
  5167. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5168. };
  5169. // Methods
  5170. /**
  5171. * Returns a new plane copied from the current Plane.
  5172. */
  5173. Plane.prototype.clone = function () {
  5174. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5175. };
  5176. /**
  5177. * Returns the string "Plane".
  5178. */
  5179. Plane.prototype.getClassName = function () {
  5180. return "Plane";
  5181. };
  5182. /**
  5183. * Returns the Plane hash code.
  5184. */
  5185. Plane.prototype.getHashCode = function () {
  5186. var hash = this.normal.getHashCode();
  5187. hash = (hash * 397) ^ (this.d || 0);
  5188. return hash;
  5189. };
  5190. /**
  5191. * Normalize the current Plane in place.
  5192. * Returns the updated Plane.
  5193. */
  5194. Plane.prototype.normalize = function () {
  5195. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5196. var magnitude = 0.0;
  5197. if (norm !== 0) {
  5198. magnitude = 1.0 / norm;
  5199. }
  5200. this.normal.x *= magnitude;
  5201. this.normal.y *= magnitude;
  5202. this.normal.z *= magnitude;
  5203. this.d *= magnitude;
  5204. return this;
  5205. };
  5206. /**
  5207. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5208. */
  5209. Plane.prototype.transform = function (transformation) {
  5210. var transposedMatrix = Matrix.Transpose(transformation);
  5211. var x = this.normal.x;
  5212. var y = this.normal.y;
  5213. var z = this.normal.z;
  5214. var d = this.d;
  5215. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5216. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5217. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5218. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5219. return new Plane(normalX, normalY, normalZ, finalD);
  5220. };
  5221. /**
  5222. * Returns the dot product (float) of the point coordinates and the plane normal.
  5223. */
  5224. Plane.prototype.dotCoordinate = function (point) {
  5225. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5226. };
  5227. /**
  5228. * Updates the current Plane from the plane defined by the three passed points.
  5229. * Returns the updated Plane.
  5230. */
  5231. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5232. var x1 = point2.x - point1.x;
  5233. var y1 = point2.y - point1.y;
  5234. var z1 = point2.z - point1.z;
  5235. var x2 = point3.x - point1.x;
  5236. var y2 = point3.y - point1.y;
  5237. var z2 = point3.z - point1.z;
  5238. var yz = (y1 * z2) - (z1 * y2);
  5239. var xz = (z1 * x2) - (x1 * z2);
  5240. var xy = (x1 * y2) - (y1 * x2);
  5241. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5242. var invPyth;
  5243. if (pyth !== 0) {
  5244. invPyth = 1.0 / pyth;
  5245. }
  5246. else {
  5247. invPyth = 0.0;
  5248. }
  5249. this.normal.x = yz * invPyth;
  5250. this.normal.y = xz * invPyth;
  5251. this.normal.z = xy * invPyth;
  5252. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5253. return this;
  5254. };
  5255. /**
  5256. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5257. */
  5258. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5259. var dot = Vector3.Dot(this.normal, direction);
  5260. return (dot <= epsilon);
  5261. };
  5262. /**
  5263. * Returns the signed distance (float) from the passed point to the Plane.
  5264. */
  5265. Plane.prototype.signedDistanceTo = function (point) {
  5266. return Vector3.Dot(point, this.normal) + this.d;
  5267. };
  5268. // Statics
  5269. /**
  5270. * Returns a new Plane from the passed array.
  5271. */
  5272. Plane.FromArray = function (array) {
  5273. return new Plane(array[0], array[1], array[2], array[3]);
  5274. };
  5275. /**
  5276. * Returns a new Plane defined by the three passed points.
  5277. */
  5278. Plane.FromPoints = function (point1, point2, point3) {
  5279. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5280. result.copyFromPoints(point1, point2, point3);
  5281. return result;
  5282. };
  5283. /**
  5284. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5285. * Note : the vector "normal" is updated because normalized.
  5286. */
  5287. Plane.FromPositionAndNormal = function (origin, normal) {
  5288. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5289. normal.normalize();
  5290. result.normal = normal;
  5291. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5292. return result;
  5293. };
  5294. /**
  5295. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5296. */
  5297. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5298. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5299. return Vector3.Dot(point, normal) + d;
  5300. };
  5301. return Plane;
  5302. }());
  5303. BABYLON.Plane = Plane;
  5304. var Viewport = /** @class */ (function () {
  5305. /**
  5306. * Creates a Viewport object located at (x, y) and sized (width, height).
  5307. */
  5308. function Viewport(x, y, width, height) {
  5309. this.x = x;
  5310. this.y = y;
  5311. this.width = width;
  5312. this.height = height;
  5313. }
  5314. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5315. if (renderWidthOrEngine.getRenderWidth) {
  5316. var engine = renderWidthOrEngine;
  5317. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5318. }
  5319. var renderWidth = renderWidthOrEngine;
  5320. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5321. };
  5322. /**
  5323. * Returns a new Viewport copied from the current one.
  5324. */
  5325. Viewport.prototype.clone = function () {
  5326. return new Viewport(this.x, this.y, this.width, this.height);
  5327. };
  5328. return Viewport;
  5329. }());
  5330. BABYLON.Viewport = Viewport;
  5331. var Frustum = /** @class */ (function () {
  5332. function Frustum() {
  5333. }
  5334. /**
  5335. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5336. */
  5337. Frustum.GetPlanes = function (transform) {
  5338. var frustumPlanes = [];
  5339. for (var index = 0; index < 6; index++) {
  5340. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5341. }
  5342. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5343. return frustumPlanes;
  5344. };
  5345. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5346. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5347. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5348. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5349. frustumPlane.d = transform.m[15] + transform.m[14];
  5350. frustumPlane.normalize();
  5351. };
  5352. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5353. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5354. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5355. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5356. frustumPlane.d = transform.m[15] - transform.m[14];
  5357. frustumPlane.normalize();
  5358. };
  5359. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5363. frustumPlane.d = transform.m[15] + transform.m[12];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5370. frustumPlane.d = transform.m[15] - transform.m[12];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5375. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5376. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5377. frustumPlane.d = transform.m[15] - transform.m[13];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5382. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5383. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5384. frustumPlane.d = transform.m[15] + transform.m[13];
  5385. frustumPlane.normalize();
  5386. };
  5387. /**
  5388. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5389. */
  5390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5391. // Near
  5392. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5393. // Far
  5394. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5395. // Left
  5396. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5397. // Right
  5398. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5399. // Top
  5400. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5401. // Bottom
  5402. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5403. };
  5404. return Frustum;
  5405. }());
  5406. BABYLON.Frustum = Frustum;
  5407. var Space;
  5408. (function (Space) {
  5409. Space[Space["LOCAL"] = 0] = "LOCAL";
  5410. Space[Space["WORLD"] = 1] = "WORLD";
  5411. Space[Space["BONE"] = 2] = "BONE";
  5412. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5413. var Axis = /** @class */ (function () {
  5414. function Axis() {
  5415. }
  5416. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5417. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5418. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5419. return Axis;
  5420. }());
  5421. BABYLON.Axis = Axis;
  5422. ;
  5423. var BezierCurve = /** @class */ (function () {
  5424. function BezierCurve() {
  5425. }
  5426. /**
  5427. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5428. */
  5429. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5430. // Extract X (which is equal to time here)
  5431. var f0 = 1 - 3 * x2 + 3 * x1;
  5432. var f1 = 3 * x2 - 6 * x1;
  5433. var f2 = 3 * x1;
  5434. var refinedT = t;
  5435. for (var i = 0; i < 5; i++) {
  5436. var refinedT2 = refinedT * refinedT;
  5437. var refinedT3 = refinedT2 * refinedT;
  5438. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5439. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5440. refinedT -= (x - t) * slope;
  5441. refinedT = Math.min(1, Math.max(0, refinedT));
  5442. }
  5443. // Resolve cubic bezier for the given x
  5444. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5445. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5446. Math.pow(refinedT, 3);
  5447. };
  5448. return BezierCurve;
  5449. }());
  5450. BABYLON.BezierCurve = BezierCurve;
  5451. var Orientation;
  5452. (function (Orientation) {
  5453. Orientation[Orientation["CW"] = 0] = "CW";
  5454. Orientation[Orientation["CCW"] = 1] = "CCW";
  5455. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5456. var Angle = /** @class */ (function () {
  5457. /**
  5458. * Creates an Angle object of "radians" radians (float).
  5459. */
  5460. function Angle(radians) {
  5461. var _this = this;
  5462. /**
  5463. * Returns the Angle value in degrees (float).
  5464. */
  5465. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5466. /**
  5467. * Returns the Angle value in radians (float).
  5468. */
  5469. this.radians = function () { return _this._radians; };
  5470. this._radians = radians;
  5471. if (this._radians < 0.0)
  5472. this._radians += (2.0 * Math.PI);
  5473. }
  5474. /**
  5475. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5476. */
  5477. Angle.BetweenTwoPoints = function (a, b) {
  5478. var delta = b.subtract(a);
  5479. var theta = Math.atan2(delta.y, delta.x);
  5480. return new Angle(theta);
  5481. };
  5482. /**
  5483. * Returns a new Angle object from the passed float in radians.
  5484. */
  5485. Angle.FromRadians = function (radians) {
  5486. return new Angle(radians);
  5487. };
  5488. /**
  5489. * Returns a new Angle object from the passed float in degrees.
  5490. */
  5491. Angle.FromDegrees = function (degrees) {
  5492. return new Angle(degrees * Math.PI / 180.0);
  5493. };
  5494. return Angle;
  5495. }());
  5496. BABYLON.Angle = Angle;
  5497. var Arc2 = /** @class */ (function () {
  5498. /**
  5499. * Creates an Arc object from the three passed points : start, middle and end.
  5500. */
  5501. function Arc2(startPoint, midPoint, endPoint) {
  5502. this.startPoint = startPoint;
  5503. this.midPoint = midPoint;
  5504. this.endPoint = endPoint;
  5505. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5506. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5507. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5508. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5509. 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);
  5510. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5511. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5512. var a1 = this.startAngle.degrees();
  5513. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5514. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5515. // angles correction
  5516. if (a2 - a1 > +180.0)
  5517. a2 -= 360.0;
  5518. if (a2 - a1 < -180.0)
  5519. a2 += 360.0;
  5520. if (a3 - a2 > +180.0)
  5521. a3 -= 360.0;
  5522. if (a3 - a2 < -180.0)
  5523. a3 += 360.0;
  5524. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5525. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5526. }
  5527. return Arc2;
  5528. }());
  5529. BABYLON.Arc2 = Arc2;
  5530. var Path2 = /** @class */ (function () {
  5531. /**
  5532. * Creates a Path2 object from the starting 2D coordinates x and y.
  5533. */
  5534. function Path2(x, y) {
  5535. this._points = new Array();
  5536. this._length = 0.0;
  5537. this.closed = false;
  5538. this._points.push(new Vector2(x, y));
  5539. }
  5540. /**
  5541. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5542. * Returns the updated Path2.
  5543. */
  5544. Path2.prototype.addLineTo = function (x, y) {
  5545. if (this.closed) {
  5546. //Tools.Error("cannot add lines to closed paths");
  5547. return this;
  5548. }
  5549. var newPoint = new Vector2(x, y);
  5550. var previousPoint = this._points[this._points.length - 1];
  5551. this._points.push(newPoint);
  5552. this._length += newPoint.subtract(previousPoint).length();
  5553. return this;
  5554. };
  5555. /**
  5556. * 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.
  5557. * Returns the updated Path2.
  5558. */
  5559. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5560. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5561. if (this.closed) {
  5562. //Tools.Error("cannot add arcs to closed paths");
  5563. return this;
  5564. }
  5565. var startPoint = this._points[this._points.length - 1];
  5566. var midPoint = new Vector2(midX, midY);
  5567. var endPoint = new Vector2(endX, endY);
  5568. var arc = new Arc2(startPoint, midPoint, endPoint);
  5569. var increment = arc.angle.radians() / numberOfSegments;
  5570. if (arc.orientation === Orientation.CW)
  5571. increment *= -1;
  5572. var currentAngle = arc.startAngle.radians() + increment;
  5573. for (var i = 0; i < numberOfSegments; i++) {
  5574. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5575. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5576. this.addLineTo(x, y);
  5577. currentAngle += increment;
  5578. }
  5579. return this;
  5580. };
  5581. /**
  5582. * Closes the Path2.
  5583. * Returns the Path2.
  5584. */
  5585. Path2.prototype.close = function () {
  5586. this.closed = true;
  5587. return this;
  5588. };
  5589. /**
  5590. * Returns the Path2 total length (float).
  5591. */
  5592. Path2.prototype.length = function () {
  5593. var result = this._length;
  5594. if (!this.closed) {
  5595. var lastPoint = this._points[this._points.length - 1];
  5596. var firstPoint = this._points[0];
  5597. result += (firstPoint.subtract(lastPoint).length());
  5598. }
  5599. return result;
  5600. };
  5601. /**
  5602. * Returns the Path2 internal array of points.
  5603. */
  5604. Path2.prototype.getPoints = function () {
  5605. return this._points;
  5606. };
  5607. /**
  5608. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5609. */
  5610. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5611. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5612. //Tools.Error("normalized length position should be between 0 and 1.");
  5613. return Vector2.Zero();
  5614. }
  5615. var lengthPosition = normalizedLengthPosition * this.length();
  5616. var previousOffset = 0;
  5617. for (var i = 0; i < this._points.length; i++) {
  5618. var j = (i + 1) % this._points.length;
  5619. var a = this._points[i];
  5620. var b = this._points[j];
  5621. var bToA = b.subtract(a);
  5622. var nextOffset = (bToA.length() + previousOffset);
  5623. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5624. var dir = bToA.normalize();
  5625. var localOffset = lengthPosition - previousOffset;
  5626. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5627. }
  5628. previousOffset = nextOffset;
  5629. }
  5630. //Tools.Error("internal error");
  5631. return Vector2.Zero();
  5632. };
  5633. /**
  5634. * Returns a new Path2 starting at the coordinates (x, y).
  5635. */
  5636. Path2.StartingAt = function (x, y) {
  5637. return new Path2(x, y);
  5638. };
  5639. return Path2;
  5640. }());
  5641. BABYLON.Path2 = Path2;
  5642. var Path3D = /** @class */ (function () {
  5643. /**
  5644. * new Path3D(path, normal, raw)
  5645. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5646. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5647. * path : an array of Vector3, the curve axis of the Path3D
  5648. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5649. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5650. */
  5651. function Path3D(path, firstNormal, raw) {
  5652. if (firstNormal === void 0) { firstNormal = null; }
  5653. this.path = path;
  5654. this._curve = new Array();
  5655. this._distances = new Array();
  5656. this._tangents = new Array();
  5657. this._normals = new Array();
  5658. this._binormals = new Array();
  5659. for (var p = 0; p < path.length; p++) {
  5660. this._curve[p] = path[p].clone(); // hard copy
  5661. }
  5662. this._raw = raw || false;
  5663. this._compute(firstNormal);
  5664. }
  5665. /**
  5666. * Returns the Path3D array of successive Vector3 designing its curve.
  5667. */
  5668. Path3D.prototype.getCurve = function () {
  5669. return this._curve;
  5670. };
  5671. /**
  5672. * Returns an array populated with tangent vectors on each Path3D curve point.
  5673. */
  5674. Path3D.prototype.getTangents = function () {
  5675. return this._tangents;
  5676. };
  5677. /**
  5678. * Returns an array populated with normal vectors on each Path3D curve point.
  5679. */
  5680. Path3D.prototype.getNormals = function () {
  5681. return this._normals;
  5682. };
  5683. /**
  5684. * Returns an array populated with binormal vectors on each Path3D curve point.
  5685. */
  5686. Path3D.prototype.getBinormals = function () {
  5687. return this._binormals;
  5688. };
  5689. /**
  5690. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5691. */
  5692. Path3D.prototype.getDistances = function () {
  5693. return this._distances;
  5694. };
  5695. /**
  5696. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5697. * Returns the same object updated.
  5698. */
  5699. Path3D.prototype.update = function (path, firstNormal) {
  5700. if (firstNormal === void 0) { firstNormal = null; }
  5701. for (var p = 0; p < path.length; p++) {
  5702. this._curve[p].x = path[p].x;
  5703. this._curve[p].y = path[p].y;
  5704. this._curve[p].z = path[p].z;
  5705. }
  5706. this._compute(firstNormal);
  5707. return this;
  5708. };
  5709. // private function compute() : computes tangents, normals and binormals
  5710. Path3D.prototype._compute = function (firstNormal) {
  5711. var l = this._curve.length;
  5712. // first and last tangents
  5713. this._tangents[0] = this._getFirstNonNullVector(0);
  5714. if (!this._raw) {
  5715. this._tangents[0].normalize();
  5716. }
  5717. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5718. if (!this._raw) {
  5719. this._tangents[l - 1].normalize();
  5720. }
  5721. // normals and binormals at first point : arbitrary vector with _normalVector()
  5722. var tg0 = this._tangents[0];
  5723. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5724. this._normals[0] = pp0;
  5725. if (!this._raw) {
  5726. this._normals[0].normalize();
  5727. }
  5728. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5729. if (!this._raw) {
  5730. this._binormals[0].normalize();
  5731. }
  5732. this._distances[0] = 0.0;
  5733. // normals and binormals : next points
  5734. var prev; // previous vector (segment)
  5735. var cur; // current vector (segment)
  5736. var curTang; // current tangent
  5737. // previous normal
  5738. var prevBinor; // previous binormal
  5739. for (var i = 1; i < l; i++) {
  5740. // tangents
  5741. prev = this._getLastNonNullVector(i);
  5742. if (i < l - 1) {
  5743. cur = this._getFirstNonNullVector(i);
  5744. this._tangents[i] = prev.add(cur);
  5745. this._tangents[i].normalize();
  5746. }
  5747. this._distances[i] = this._distances[i - 1] + prev.length();
  5748. // normals and binormals
  5749. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5750. curTang = this._tangents[i];
  5751. prevBinor = this._binormals[i - 1];
  5752. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5753. if (!this._raw) {
  5754. this._normals[i].normalize();
  5755. }
  5756. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5757. if (!this._raw) {
  5758. this._binormals[i].normalize();
  5759. }
  5760. }
  5761. };
  5762. // private function getFirstNonNullVector(index)
  5763. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5764. Path3D.prototype._getFirstNonNullVector = function (index) {
  5765. var i = 1;
  5766. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5767. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5768. i++;
  5769. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5770. }
  5771. return nNVector;
  5772. };
  5773. // private function getLastNonNullVector(index)
  5774. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5775. Path3D.prototype._getLastNonNullVector = function (index) {
  5776. var i = 1;
  5777. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5778. while (nLVector.length() === 0 && index > i + 1) {
  5779. i++;
  5780. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5781. }
  5782. return nLVector;
  5783. };
  5784. // private function normalVector(v0, vt, va) :
  5785. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5786. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5787. Path3D.prototype._normalVector = function (v0, vt, va) {
  5788. var normal0;
  5789. var tgl = vt.length();
  5790. if (tgl === 0.0) {
  5791. tgl = 1.0;
  5792. }
  5793. if (va === undefined || va === null) {
  5794. var point;
  5795. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5796. point = new Vector3(0.0, -1.0, 0.0);
  5797. }
  5798. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5799. point = new Vector3(1.0, 0.0, 0.0);
  5800. }
  5801. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5802. point = new Vector3(0.0, 0.0, 1.0);
  5803. }
  5804. else {
  5805. point = Vector3.Zero();
  5806. }
  5807. normal0 = Vector3.Cross(vt, point);
  5808. }
  5809. else {
  5810. normal0 = Vector3.Cross(vt, va);
  5811. Vector3.CrossToRef(normal0, vt, normal0);
  5812. }
  5813. normal0.normalize();
  5814. return normal0;
  5815. };
  5816. return Path3D;
  5817. }());
  5818. BABYLON.Path3D = Path3D;
  5819. var Curve3 = /** @class */ (function () {
  5820. /**
  5821. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5822. * A Curve3 is designed from a series of successive Vector3.
  5823. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5824. */
  5825. function Curve3(points) {
  5826. this._length = 0.0;
  5827. this._points = points;
  5828. this._length = this._computeLength(points);
  5829. }
  5830. /**
  5831. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5832. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5833. * @param v1 (Vector3) the control point
  5834. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5835. * @param nbPoints (integer) the wanted number of points in the curve
  5836. */
  5837. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5838. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5839. var bez = new Array();
  5840. var equation = function (t, val0, val1, val2) {
  5841. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5842. return res;
  5843. };
  5844. for (var i = 0; i <= nbPoints; i++) {
  5845. 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)));
  5846. }
  5847. return new Curve3(bez);
  5848. };
  5849. /**
  5850. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5851. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5852. * @param v1 (Vector3) the first control point
  5853. * @param v2 (Vector3) the second control point
  5854. * @param v3 (Vector3) the end point of the Cubic Bezier
  5855. * @param nbPoints (integer) the wanted number of points in the curve
  5856. */
  5857. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5858. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5859. var bez = new Array();
  5860. var equation = function (t, val0, val1, val2, val3) {
  5861. 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;
  5862. return res;
  5863. };
  5864. for (var i = 0; i <= nbPoints; i++) {
  5865. 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)));
  5866. }
  5867. return new Curve3(bez);
  5868. };
  5869. /**
  5870. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5871. * @param p1 (Vector3) the origin point of the Hermite Spline
  5872. * @param t1 (Vector3) the tangent vector at the origin point
  5873. * @param p2 (Vector3) the end point of the Hermite Spline
  5874. * @param t2 (Vector3) the tangent vector at the end point
  5875. * @param nbPoints (integer) the wanted number of points in the curve
  5876. */
  5877. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5878. var hermite = new Array();
  5879. var step = 1.0 / nbPoints;
  5880. for (var i = 0; i <= nbPoints; i++) {
  5881. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5882. }
  5883. return new Curve3(hermite);
  5884. };
  5885. /**
  5886. * Returns a Curve3 object along a CatmullRom Spline curve :
  5887. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5888. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5889. */
  5890. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5891. var totalPoints = new Array();
  5892. totalPoints.push(points[0].clone());
  5893. Array.prototype.push.apply(totalPoints, points);
  5894. totalPoints.push(points[points.length - 1].clone());
  5895. var catmullRom = new Array();
  5896. var step = 1.0 / nbPoints;
  5897. var amount = 0.0;
  5898. for (var i = 0; i < totalPoints.length - 3; i++) {
  5899. amount = 0;
  5900. for (var c = 0; c < nbPoints; c++) {
  5901. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5902. amount += step;
  5903. }
  5904. }
  5905. i--;
  5906. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5907. return new Curve3(catmullRom);
  5908. };
  5909. /**
  5910. * Returns the Curve3 stored array of successive Vector3
  5911. */
  5912. Curve3.prototype.getPoints = function () {
  5913. return this._points;
  5914. };
  5915. /**
  5916. * Returns the computed length (float) of the curve.
  5917. */
  5918. Curve3.prototype.length = function () {
  5919. return this._length;
  5920. };
  5921. /**
  5922. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5923. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5924. * curveA and curveB keep unchanged.
  5925. */
  5926. Curve3.prototype.continue = function (curve) {
  5927. var lastPoint = this._points[this._points.length - 1];
  5928. var continuedPoints = this._points.slice();
  5929. var curvePoints = curve.getPoints();
  5930. for (var i = 1; i < curvePoints.length; i++) {
  5931. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5932. }
  5933. var continuedCurve = new Curve3(continuedPoints);
  5934. return continuedCurve;
  5935. };
  5936. Curve3.prototype._computeLength = function (path) {
  5937. var l = 0;
  5938. for (var i = 1; i < path.length; i++) {
  5939. l += (path[i].subtract(path[i - 1])).length();
  5940. }
  5941. return l;
  5942. };
  5943. return Curve3;
  5944. }());
  5945. BABYLON.Curve3 = Curve3;
  5946. // Vertex formats
  5947. var PositionNormalVertex = /** @class */ (function () {
  5948. function PositionNormalVertex(position, normal) {
  5949. if (position === void 0) { position = Vector3.Zero(); }
  5950. if (normal === void 0) { normal = Vector3.Up(); }
  5951. this.position = position;
  5952. this.normal = normal;
  5953. }
  5954. PositionNormalVertex.prototype.clone = function () {
  5955. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5956. };
  5957. return PositionNormalVertex;
  5958. }());
  5959. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5960. var PositionNormalTextureVertex = /** @class */ (function () {
  5961. function PositionNormalTextureVertex(position, normal, uv) {
  5962. if (position === void 0) { position = Vector3.Zero(); }
  5963. if (normal === void 0) { normal = Vector3.Up(); }
  5964. if (uv === void 0) { uv = Vector2.Zero(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. this.uv = uv;
  5968. }
  5969. PositionNormalTextureVertex.prototype.clone = function () {
  5970. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5971. };
  5972. return PositionNormalTextureVertex;
  5973. }());
  5974. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5975. // Temporary pre-allocated objects for engine internal use
  5976. // usage in any internal function :
  5977. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5978. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5979. var Tmp = /** @class */ (function () {
  5980. function Tmp() {
  5981. }
  5982. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5983. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5984. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5985. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5986. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5987. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5988. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5989. Matrix.Zero(), Matrix.Zero(),
  5990. Matrix.Zero(), Matrix.Zero(),
  5991. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5992. return Tmp;
  5993. }());
  5994. BABYLON.Tmp = Tmp;
  5995. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5996. var MathTmp = /** @class */ (function () {
  5997. function MathTmp() {
  5998. }
  5999. MathTmp.Vector3 = [Vector3.Zero()];
  6000. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6001. MathTmp.Quaternion = [Quaternion.Zero()];
  6002. return MathTmp;
  6003. }());
  6004. })(BABYLON || (BABYLON = {}));
  6005. //# sourceMappingURL=babylon.math.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var Scalar = /** @class */ (function () {
  6009. function Scalar() {
  6010. }
  6011. /**
  6012. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6013. */
  6014. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6015. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6016. var num = a - b;
  6017. return -epsilon <= num && num <= epsilon;
  6018. };
  6019. /**
  6020. * Returns a string : the upper case translation of the number i to hexadecimal.
  6021. */
  6022. Scalar.ToHex = function (i) {
  6023. var str = i.toString(16);
  6024. if (i <= 15) {
  6025. return ("0" + str).toUpperCase();
  6026. }
  6027. return str.toUpperCase();
  6028. };
  6029. /**
  6030. * Returns -1 if value is negative and +1 is value is positive.
  6031. * Returns the value itself if it's equal to zero.
  6032. */
  6033. Scalar.Sign = function (value) {
  6034. value = +value; // convert to a number
  6035. if (value === 0 || isNaN(value))
  6036. return value;
  6037. return value > 0 ? 1 : -1;
  6038. };
  6039. /**
  6040. * Returns the value itself if it's between min and max.
  6041. * Returns min if the value is lower than min.
  6042. * Returns max if the value is greater than max.
  6043. */
  6044. Scalar.Clamp = function (value, min, max) {
  6045. if (min === void 0) { min = 0; }
  6046. if (max === void 0) { max = 1; }
  6047. return Math.min(max, Math.max(min, value));
  6048. };
  6049. /**
  6050. * Returns the log2 of value.
  6051. */
  6052. Scalar.Log2 = function (value) {
  6053. return Math.log(value) * Math.LOG2E;
  6054. };
  6055. /**
  6056. * Loops the value, so that it is never larger than length and never smaller than 0.
  6057. *
  6058. * This is similar to the modulo operator but it works with floating point numbers.
  6059. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6060. * With t = 5 and length = 2.5, the result would be 0.0.
  6061. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6062. */
  6063. Scalar.Repeat = function (value, length) {
  6064. return value - Math.floor(value / length) * length;
  6065. };
  6066. /**
  6067. * Normalize the value between 0.0 and 1.0 using min and max values
  6068. */
  6069. Scalar.Normalize = function (value, min, max) {
  6070. return (value - min) / (max - min);
  6071. };
  6072. /**
  6073. * Denormalize the value from 0.0 and 1.0 using min and max values
  6074. */
  6075. Scalar.Denormalize = function (normalized, min, max) {
  6076. return (normalized * (max - min) + min);
  6077. };
  6078. /**
  6079. * Calculates the shortest difference between two given angles given in degrees.
  6080. */
  6081. Scalar.DeltaAngle = function (current, target) {
  6082. var num = Scalar.Repeat(target - current, 360.0);
  6083. if (num > 180.0) {
  6084. num -= 360.0;
  6085. }
  6086. return num;
  6087. };
  6088. /**
  6089. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6090. *
  6091. * The returned value will move back and forth between 0 and length
  6092. */
  6093. Scalar.PingPong = function (tx, length) {
  6094. var t = Scalar.Repeat(tx, length * 2.0);
  6095. return length - Math.abs(t - length);
  6096. };
  6097. /**
  6098. * Interpolates between min and max with smoothing at the limits.
  6099. *
  6100. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6101. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6102. */
  6103. Scalar.SmoothStep = function (from, to, tx) {
  6104. var t = Scalar.Clamp(tx);
  6105. t = -2.0 * t * t * t + 3.0 * t * t;
  6106. return to * t + from * (1.0 - t);
  6107. };
  6108. /**
  6109. * Moves a value current towards target.
  6110. *
  6111. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6112. * Negative values of maxDelta pushes the value away from target.
  6113. */
  6114. Scalar.MoveTowards = function (current, target, maxDelta) {
  6115. var result = 0;
  6116. if (Math.abs(target - current) <= maxDelta) {
  6117. result = target;
  6118. }
  6119. else {
  6120. result = current + Scalar.Sign(target - current) * maxDelta;
  6121. }
  6122. return result;
  6123. };
  6124. /**
  6125. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6126. *
  6127. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6128. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6129. */
  6130. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6131. var num = Scalar.DeltaAngle(current, target);
  6132. var result = 0;
  6133. if (-maxDelta < num && num < maxDelta) {
  6134. result = target;
  6135. }
  6136. else {
  6137. target = current + num;
  6138. result = Scalar.MoveTowards(current, target, maxDelta);
  6139. }
  6140. return result;
  6141. };
  6142. /**
  6143. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6144. */
  6145. Scalar.Lerp = function (start, end, amount) {
  6146. return start + ((end - start) * amount);
  6147. };
  6148. /**
  6149. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6150. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6151. */
  6152. Scalar.LerpAngle = function (start, end, amount) {
  6153. var num = Scalar.Repeat(end - start, 360.0);
  6154. if (num > 180.0) {
  6155. num -= 360.0;
  6156. }
  6157. return start + num * Scalar.Clamp(amount);
  6158. };
  6159. /**
  6160. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6161. */
  6162. Scalar.InverseLerp = function (a, b, value) {
  6163. var result = 0;
  6164. if (a != b) {
  6165. result = Scalar.Clamp((value - a) / (b - a));
  6166. }
  6167. else {
  6168. result = 0.0;
  6169. }
  6170. return result;
  6171. };
  6172. /**
  6173. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6174. */
  6175. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6176. var squared = amount * amount;
  6177. var cubed = amount * squared;
  6178. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6179. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6180. var part3 = (cubed - (2.0 * squared)) + amount;
  6181. var part4 = cubed - squared;
  6182. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6183. };
  6184. /**
  6185. * Returns a random float number between and min and max values
  6186. */
  6187. Scalar.RandomRange = function (min, max) {
  6188. if (min === max)
  6189. return min;
  6190. return ((Math.random() * (max - min)) + min);
  6191. };
  6192. /**
  6193. * This function returns percentage of a number in a given range.
  6194. *
  6195. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6196. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6197. */
  6198. Scalar.RangeToPercent = function (number, min, max) {
  6199. return ((number - min) / (max - min));
  6200. };
  6201. /**
  6202. * This function returns number that corresponds to the percentage in a given range.
  6203. *
  6204. * PercentToRange(0.34,0,100) will return 34.
  6205. */
  6206. Scalar.PercentToRange = function (percent, min, max) {
  6207. return ((max - min) * percent + min);
  6208. };
  6209. /**
  6210. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6211. * @param angle The angle to normalize in radian.
  6212. * @return The converted angle.
  6213. */
  6214. Scalar.NormalizeRadians = function (angle) {
  6215. // More precise but slower version kept for reference.
  6216. // angle = angle % Tools.TwoPi;
  6217. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6218. //if (angle > Math.PI) {
  6219. // angle -= Tools.TwoPi;
  6220. //}
  6221. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6222. return angle;
  6223. };
  6224. /**
  6225. * Two pi constants convenient for computation.
  6226. */
  6227. Scalar.TwoPi = Math.PI * 2;
  6228. return Scalar;
  6229. }());
  6230. BABYLON.Scalar = Scalar;
  6231. })(BABYLON || (BABYLON = {}));
  6232. //# sourceMappingURL=babylon.math.scalar.js.map
  6233. //# sourceMappingURL=babylon.mixins.js.map
  6234. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6235. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6236. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6237. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6238. //# sourceMappingURL=babylon.webgl2.js.map
  6239. var BABYLON;
  6240. (function (BABYLON) {
  6241. var __decoratorInitialStore = {};
  6242. var __mergedStore = {};
  6243. var _copySource = function (creationFunction, source, instanciate) {
  6244. var destination = creationFunction();
  6245. // Tags
  6246. if (BABYLON.Tags) {
  6247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6248. }
  6249. var classStore = getMergedStore(destination);
  6250. // Properties
  6251. for (var property in classStore) {
  6252. var propertyDescriptor = classStore[property];
  6253. var sourceProperty = source[property];
  6254. var propertyType = propertyDescriptor.type;
  6255. if (sourceProperty !== undefined && sourceProperty !== null) {
  6256. switch (propertyType) {
  6257. case 0: // Value
  6258. case 6:// Mesh reference
  6259. destination[property] = sourceProperty;
  6260. break;
  6261. case 1:// Texture
  6262. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6263. break;
  6264. case 2: // Color3
  6265. case 3: // FresnelParameters
  6266. case 4: // Vector2
  6267. case 5: // Vector3
  6268. case 7: // Color Curves
  6269. case 10:// Quaternion
  6270. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6271. break;
  6272. }
  6273. }
  6274. }
  6275. return destination;
  6276. };
  6277. function getDirectStore(target) {
  6278. var classKey = target.getClassName();
  6279. if (!__decoratorInitialStore[classKey]) {
  6280. __decoratorInitialStore[classKey] = {};
  6281. }
  6282. return __decoratorInitialStore[classKey];
  6283. }
  6284. /**
  6285. * Return the list of properties flagged as serializable
  6286. * @param target: host object
  6287. */
  6288. function getMergedStore(target) {
  6289. var classKey = target.getClassName();
  6290. if (__mergedStore[classKey]) {
  6291. return __mergedStore[classKey];
  6292. }
  6293. __mergedStore[classKey] = {};
  6294. var store = __mergedStore[classKey];
  6295. var currentTarget = target;
  6296. var currentKey = classKey;
  6297. while (currentKey) {
  6298. var initialStore = __decoratorInitialStore[currentKey];
  6299. for (var property in initialStore) {
  6300. store[property] = initialStore[property];
  6301. }
  6302. var parent_1 = void 0;
  6303. var done = false;
  6304. do {
  6305. parent_1 = Object.getPrototypeOf(currentTarget);
  6306. if (!parent_1.getClassName) {
  6307. done = true;
  6308. break;
  6309. }
  6310. if (parent_1.getClassName() !== currentKey) {
  6311. break;
  6312. }
  6313. currentTarget = parent_1;
  6314. } while (parent_1);
  6315. if (done) {
  6316. break;
  6317. }
  6318. currentKey = parent_1.getClassName();
  6319. currentTarget = parent_1;
  6320. }
  6321. return store;
  6322. }
  6323. function generateSerializableMember(type, sourceName) {
  6324. return function (target, propertyKey) {
  6325. var classStore = getDirectStore(target);
  6326. if (!classStore[propertyKey]) {
  6327. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6328. }
  6329. };
  6330. }
  6331. function generateExpandMember(setCallback, targetKey) {
  6332. if (targetKey === void 0) { targetKey = null; }
  6333. return function (target, propertyKey) {
  6334. var key = targetKey || ("_" + propertyKey);
  6335. Object.defineProperty(target, propertyKey, {
  6336. get: function () {
  6337. return this[key];
  6338. },
  6339. set: function (value) {
  6340. if (this[key] === value) {
  6341. return;
  6342. }
  6343. this[key] = value;
  6344. target[setCallback].apply(this);
  6345. },
  6346. enumerable: true,
  6347. configurable: true
  6348. });
  6349. };
  6350. }
  6351. function expandToProperty(callback, targetKey) {
  6352. if (targetKey === void 0) { targetKey = null; }
  6353. return generateExpandMember(callback, targetKey);
  6354. }
  6355. BABYLON.expandToProperty = expandToProperty;
  6356. function serialize(sourceName) {
  6357. return generateSerializableMember(0, sourceName); // value member
  6358. }
  6359. BABYLON.serialize = serialize;
  6360. function serializeAsTexture(sourceName) {
  6361. return generateSerializableMember(1, sourceName); // texture member
  6362. }
  6363. BABYLON.serializeAsTexture = serializeAsTexture;
  6364. function serializeAsColor3(sourceName) {
  6365. return generateSerializableMember(2, sourceName); // color3 member
  6366. }
  6367. BABYLON.serializeAsColor3 = serializeAsColor3;
  6368. function serializeAsFresnelParameters(sourceName) {
  6369. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6370. }
  6371. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6372. function serializeAsVector2(sourceName) {
  6373. return generateSerializableMember(4, sourceName); // vector2 member
  6374. }
  6375. BABYLON.serializeAsVector2 = serializeAsVector2;
  6376. function serializeAsVector3(sourceName) {
  6377. return generateSerializableMember(5, sourceName); // vector3 member
  6378. }
  6379. BABYLON.serializeAsVector3 = serializeAsVector3;
  6380. function serializeAsMeshReference(sourceName) {
  6381. return generateSerializableMember(6, sourceName); // mesh reference member
  6382. }
  6383. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6384. function serializeAsColorCurves(sourceName) {
  6385. return generateSerializableMember(7, sourceName); // color curves
  6386. }
  6387. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6388. function serializeAsColor4(sourceName) {
  6389. return generateSerializableMember(8, sourceName); // color 4
  6390. }
  6391. BABYLON.serializeAsColor4 = serializeAsColor4;
  6392. function serializeAsImageProcessingConfiguration(sourceName) {
  6393. return generateSerializableMember(9, sourceName); // image processing
  6394. }
  6395. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6396. function serializeAsQuaternion(sourceName) {
  6397. return generateSerializableMember(10, sourceName); // quaternion member
  6398. }
  6399. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6400. var SerializationHelper = /** @class */ (function () {
  6401. function SerializationHelper() {
  6402. }
  6403. SerializationHelper.Serialize = function (entity, serializationObject) {
  6404. if (!serializationObject) {
  6405. serializationObject = {};
  6406. }
  6407. // Tags
  6408. if (BABYLON.Tags) {
  6409. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6410. }
  6411. var serializedProperties = getMergedStore(entity);
  6412. // Properties
  6413. for (var property in serializedProperties) {
  6414. var propertyDescriptor = serializedProperties[property];
  6415. var targetPropertyName = propertyDescriptor.sourceName || property;
  6416. var propertyType = propertyDescriptor.type;
  6417. var sourceProperty = entity[property];
  6418. if (sourceProperty !== undefined && sourceProperty !== null) {
  6419. switch (propertyType) {
  6420. case 0:// Value
  6421. serializationObject[targetPropertyName] = sourceProperty;
  6422. break;
  6423. case 1:// Texture
  6424. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6425. break;
  6426. case 2:// Color3
  6427. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6428. break;
  6429. case 3:// FresnelParameters
  6430. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6431. break;
  6432. case 4:// Vector2
  6433. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6434. break;
  6435. case 5:// Vector3
  6436. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6437. break;
  6438. case 6:// Mesh reference
  6439. serializationObject[targetPropertyName] = sourceProperty.id;
  6440. break;
  6441. case 7:// Color Curves
  6442. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6443. break;
  6444. case 8:// Color 4
  6445. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6446. break;
  6447. case 9:// Image Processing
  6448. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. return serializationObject;
  6454. };
  6455. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6456. if (rootUrl === void 0) { rootUrl = null; }
  6457. var destination = creationFunction();
  6458. if (!rootUrl) {
  6459. rootUrl = "";
  6460. }
  6461. // Tags
  6462. if (BABYLON.Tags) {
  6463. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6464. }
  6465. var classStore = getMergedStore(destination);
  6466. // Properties
  6467. for (var property in classStore) {
  6468. var propertyDescriptor = classStore[property];
  6469. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6470. var propertyType = propertyDescriptor.type;
  6471. if (sourceProperty !== undefined && sourceProperty !== null) {
  6472. var dest = destination;
  6473. switch (propertyType) {
  6474. case 0:// Value
  6475. dest[property] = sourceProperty;
  6476. break;
  6477. case 1:// Texture
  6478. if (scene) {
  6479. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6480. }
  6481. break;
  6482. case 2:// Color3
  6483. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6484. break;
  6485. case 3:// FresnelParameters
  6486. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6487. break;
  6488. case 4:// Vector2
  6489. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6490. break;
  6491. case 5:// Vector3
  6492. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6493. break;
  6494. case 6:// Mesh reference
  6495. if (scene) {
  6496. dest[property] = scene.getLastMeshByID(sourceProperty);
  6497. }
  6498. break;
  6499. case 7:// Color Curves
  6500. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6501. break;
  6502. case 8:// Color 4
  6503. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6504. break;
  6505. case 9:// Image Processing
  6506. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6507. break;
  6508. }
  6509. }
  6510. }
  6511. return destination;
  6512. };
  6513. SerializationHelper.Clone = function (creationFunction, source) {
  6514. return _copySource(creationFunction, source, false);
  6515. };
  6516. SerializationHelper.Instanciate = function (creationFunction, source) {
  6517. return _copySource(creationFunction, source, true);
  6518. };
  6519. return SerializationHelper;
  6520. }());
  6521. BABYLON.SerializationHelper = SerializationHelper;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.decorators.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. /**
  6527. * A class serves as a medium between the observable and its observers
  6528. */
  6529. var EventState = /** @class */ (function () {
  6530. /**
  6531. * Create a new EventState
  6532. * @param mask defines the mask associated with this state
  6533. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  6534. * @param target defines the original target of the state
  6535. * @param currentTarget defines the current target of the state
  6536. */
  6537. function EventState(mask, skipNextObservers, target, currentTarget) {
  6538. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6539. this.initalize(mask, skipNextObservers, target, currentTarget);
  6540. }
  6541. /**
  6542. * Initialize the current event state
  6543. * @param mask defines the mask associated with this state
  6544. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  6545. * @param target defines the original target of the state
  6546. * @param currentTarget defines the current target of the state
  6547. * @returns the current event state
  6548. */
  6549. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6550. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6551. this.mask = mask;
  6552. this.skipNextObservers = skipNextObservers;
  6553. this.target = target;
  6554. this.currentTarget = currentTarget;
  6555. return this;
  6556. };
  6557. return EventState;
  6558. }());
  6559. BABYLON.EventState = EventState;
  6560. /**
  6561. * Represent an Observer registered to a given Observable object.
  6562. */
  6563. var Observer = /** @class */ (function () {
  6564. /**
  6565. * Creates a new observer
  6566. * @param callback defines the callback to call when the observer is notified
  6567. * @param mask defines the mask of the observer (used to filter notifications)
  6568. * @param scope defines the current scope used to restore the JS context
  6569. */
  6570. function Observer(
  6571. /**
  6572. * Defines the callback to call when the observer is notified
  6573. */
  6574. callback,
  6575. /**
  6576. * Defines the mask of the observer (used to filter notifications)
  6577. */
  6578. mask,
  6579. /**
  6580. * Defines the current scope used to restore the JS context
  6581. */
  6582. scope) {
  6583. if (scope === void 0) { scope = null; }
  6584. this.callback = callback;
  6585. this.mask = mask;
  6586. this.scope = scope;
  6587. /**
  6588. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  6589. */
  6590. this.unregisterOnNextCall = false;
  6591. }
  6592. return Observer;
  6593. }());
  6594. BABYLON.Observer = Observer;
  6595. /**
  6596. * Represent a list of observers registered to multiple Observables object.
  6597. */
  6598. var MultiObserver = /** @class */ (function () {
  6599. function MultiObserver() {
  6600. }
  6601. /**
  6602. * Release associated resources
  6603. */
  6604. MultiObserver.prototype.dispose = function () {
  6605. if (this._observers && this._observables) {
  6606. for (var index = 0; index < this._observers.length; index++) {
  6607. this._observables[index].remove(this._observers[index]);
  6608. }
  6609. }
  6610. this._observers = null;
  6611. this._observables = null;
  6612. };
  6613. /**
  6614. * Raise a callback when one of the observable will notify
  6615. * @param observables defines a list of observables to watch
  6616. * @param callback defines the callback to call on notification
  6617. * @param mask defines the mask used to filter notifications
  6618. * @param scope defines the current scope used to restore the JS context
  6619. * @returns the new MultiObserver
  6620. */
  6621. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6622. if (mask === void 0) { mask = -1; }
  6623. if (scope === void 0) { scope = null; }
  6624. var result = new MultiObserver();
  6625. result._observers = new Array();
  6626. result._observables = observables;
  6627. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6628. var observable = observables_1[_i];
  6629. var observer = observable.add(callback, mask, false, scope);
  6630. if (observer) {
  6631. result._observers.push(observer);
  6632. }
  6633. }
  6634. return result;
  6635. };
  6636. return MultiObserver;
  6637. }());
  6638. BABYLON.MultiObserver = MultiObserver;
  6639. /**
  6640. * The Observable class is a simple implementation of the Observable pattern.
  6641. * 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.
  6642. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6643. * 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).
  6644. * 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.
  6645. */
  6646. var Observable = /** @class */ (function () {
  6647. /**
  6648. * Creates a new observable
  6649. * @param onObserverAdded defines a callback to call when a new observer is added
  6650. */
  6651. function Observable(onObserverAdded) {
  6652. this._observers = new Array();
  6653. this._eventState = new EventState(0);
  6654. if (onObserverAdded) {
  6655. this._onObserverAdded = onObserverAdded;
  6656. }
  6657. }
  6658. /**
  6659. * Create a new Observer with the specified callback
  6660. * @param callback the callback that will be executed for that Observer
  6661. * @param mask the mask used to filter observers
  6662. * @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.
  6663. * @param scope optional scope for the callback to be called from
  6664. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  6665. * @returns the new observer created for the callback
  6666. */
  6667. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  6668. if (mask === void 0) { mask = -1; }
  6669. if (insertFirst === void 0) { insertFirst = false; }
  6670. if (scope === void 0) { scope = null; }
  6671. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  6672. if (!callback) {
  6673. return null;
  6674. }
  6675. var observer = new Observer(callback, mask, scope);
  6676. observer.unregisterOnNextCall = unregisterOnFirstCall;
  6677. if (insertFirst) {
  6678. this._observers.unshift(observer);
  6679. }
  6680. else {
  6681. this._observers.push(observer);
  6682. }
  6683. if (this._onObserverAdded) {
  6684. this._onObserverAdded(observer);
  6685. }
  6686. return observer;
  6687. };
  6688. /**
  6689. * Remove an Observer from the Observable object
  6690. * @param observer the instance of the Observer to remove
  6691. * @returns false if it doesn't belong to this Observable
  6692. */
  6693. Observable.prototype.remove = function (observer) {
  6694. if (!observer) {
  6695. return false;
  6696. }
  6697. var index = this._observers.indexOf(observer);
  6698. if (index !== -1) {
  6699. this._observers.splice(index, 1);
  6700. return true;
  6701. }
  6702. return false;
  6703. };
  6704. /**
  6705. * Remove a callback from the Observable object
  6706. * @param callback the callback to remove
  6707. * @param scope optional scope. If used only the callbacks with this scope will be removed
  6708. * @returns false if it doesn't belong to this Observable
  6709. */
  6710. Observable.prototype.removeCallback = function (callback, scope) {
  6711. for (var index = 0; index < this._observers.length; index++) {
  6712. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6713. this._observers.splice(index, 1);
  6714. return true;
  6715. }
  6716. }
  6717. return false;
  6718. };
  6719. Observable.prototype._deferUnregister = function (observer) {
  6720. var _this = this;
  6721. BABYLON.Tools.SetImmediate(function () {
  6722. _this.remove(observer);
  6723. });
  6724. };
  6725. /**
  6726. * Notify all Observers by calling their respective callback with the given data
  6727. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6728. * @param eventData defines the data to send to all observers
  6729. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  6730. * @param target defines the original target of the state
  6731. * @param currentTarget defines the current target of the state
  6732. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  6733. */
  6734. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6735. if (mask === void 0) { mask = -1; }
  6736. if (!this._observers.length) {
  6737. return true;
  6738. }
  6739. var state = this._eventState;
  6740. state.mask = mask;
  6741. state.target = target;
  6742. state.currentTarget = currentTarget;
  6743. state.skipNextObservers = false;
  6744. state.lastReturnValue = eventData;
  6745. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6746. var obs = _a[_i];
  6747. if (obs.mask & mask) {
  6748. if (obs.scope) {
  6749. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6750. }
  6751. else {
  6752. state.lastReturnValue = obs.callback(eventData, state);
  6753. }
  6754. if (obs.unregisterOnNextCall) {
  6755. this._deferUnregister(obs);
  6756. }
  6757. }
  6758. if (state.skipNextObservers) {
  6759. return false;
  6760. }
  6761. }
  6762. return true;
  6763. };
  6764. /**
  6765. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6766. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6767. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6768. * and it is crucial that all callbacks will be executed.
  6769. * The order of the callbacks is kept, callbacks are not executed parallel.
  6770. *
  6771. * @param eventData The data to be sent to each callback
  6772. * @param mask is used to filter observers defaults to -1
  6773. * @param target defines the callback target (see EventState)
  6774. * @param currentTarget defines he current object in the bubbling phase
  6775. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6776. */
  6777. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6778. var _this = this;
  6779. if (mask === void 0) { mask = -1; }
  6780. // create an empty promise
  6781. var p = Promise.resolve(eventData);
  6782. // no observers? return this promise.
  6783. if (!this._observers.length) {
  6784. return p;
  6785. }
  6786. var state = this._eventState;
  6787. state.mask = mask;
  6788. state.target = target;
  6789. state.currentTarget = currentTarget;
  6790. state.skipNextObservers = false;
  6791. // execute one callback after another (not using Promise.all, the order is important)
  6792. this._observers.forEach(function (obs) {
  6793. if (state.skipNextObservers) {
  6794. return;
  6795. }
  6796. if (obs.mask & mask) {
  6797. if (obs.scope) {
  6798. p = p.then(function (lastReturnedValue) {
  6799. state.lastReturnValue = lastReturnedValue;
  6800. return obs.callback.apply(obs.scope, [eventData, state]);
  6801. });
  6802. }
  6803. else {
  6804. p = p.then(function (lastReturnedValue) {
  6805. state.lastReturnValue = lastReturnedValue;
  6806. return obs.callback(eventData, state);
  6807. });
  6808. }
  6809. if (obs.unregisterOnNextCall) {
  6810. _this._deferUnregister(obs);
  6811. }
  6812. }
  6813. });
  6814. // return the eventData
  6815. return p.then(function () { return eventData; });
  6816. };
  6817. /**
  6818. * Notify a specific observer
  6819. * @param observer defines the observer to notify
  6820. * @param eventData defines the data to be sent to each callback
  6821. * @param mask is used to filter observers defaults to -1
  6822. */
  6823. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6824. if (mask === void 0) { mask = -1; }
  6825. var state = this._eventState;
  6826. state.mask = mask;
  6827. state.skipNextObservers = false;
  6828. observer.callback(eventData, state);
  6829. };
  6830. /**
  6831. * Gets a boolean indicating if the observable has at least one observer
  6832. * @returns true is the Observable has at least one Observer registered
  6833. */
  6834. Observable.prototype.hasObservers = function () {
  6835. return this._observers.length > 0;
  6836. };
  6837. /**
  6838. * Clear the list of observers
  6839. */
  6840. Observable.prototype.clear = function () {
  6841. this._observers = new Array();
  6842. this._onObserverAdded = null;
  6843. };
  6844. /**
  6845. * Clone the current observable
  6846. * @returns a new observable
  6847. */
  6848. Observable.prototype.clone = function () {
  6849. var result = new Observable();
  6850. result._observers = this._observers.slice(0);
  6851. return result;
  6852. };
  6853. /**
  6854. * Does this observable handles observer registered with a given mask
  6855. * @param mask defines the mask to be tested
  6856. * @return whether or not one observer registered with the given mask is handeled
  6857. **/
  6858. Observable.prototype.hasSpecificMask = function (mask) {
  6859. if (mask === void 0) { mask = -1; }
  6860. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6861. var obs = _a[_i];
  6862. if (obs.mask & mask || obs.mask === mask) {
  6863. return true;
  6864. }
  6865. }
  6866. return false;
  6867. };
  6868. return Observable;
  6869. }());
  6870. BABYLON.Observable = Observable;
  6871. })(BABYLON || (BABYLON = {}));
  6872. //# sourceMappingURL=babylon.observable.js.map
  6873. var BABYLON;
  6874. (function (BABYLON) {
  6875. var SmartArray = /** @class */ (function () {
  6876. function SmartArray(capacity) {
  6877. this.length = 0;
  6878. this.data = new Array(capacity);
  6879. this._id = SmartArray._GlobalId++;
  6880. }
  6881. SmartArray.prototype.push = function (value) {
  6882. this.data[this.length++] = value;
  6883. if (this.length > this.data.length) {
  6884. this.data.length *= 2;
  6885. }
  6886. };
  6887. SmartArray.prototype.forEach = function (func) {
  6888. for (var index = 0; index < this.length; index++) {
  6889. func(this.data[index]);
  6890. }
  6891. };
  6892. SmartArray.prototype.sort = function (compareFn) {
  6893. this.data.sort(compareFn);
  6894. };
  6895. SmartArray.prototype.reset = function () {
  6896. this.length = 0;
  6897. };
  6898. SmartArray.prototype.dispose = function () {
  6899. this.reset();
  6900. if (this.data) {
  6901. this.data.length = 0;
  6902. this.data = [];
  6903. }
  6904. };
  6905. SmartArray.prototype.concat = function (array) {
  6906. if (array.length === 0) {
  6907. return;
  6908. }
  6909. if (this.length + array.length > this.data.length) {
  6910. this.data.length = (this.length + array.length) * 2;
  6911. }
  6912. for (var index = 0; index < array.length; index++) {
  6913. this.data[this.length++] = (array.data || array)[index];
  6914. }
  6915. };
  6916. SmartArray.prototype.indexOf = function (value) {
  6917. var position = this.data.indexOf(value);
  6918. if (position >= this.length) {
  6919. return -1;
  6920. }
  6921. return position;
  6922. };
  6923. SmartArray.prototype.contains = function (value) {
  6924. return this.data.indexOf(value) !== -1;
  6925. };
  6926. // Statics
  6927. SmartArray._GlobalId = 0;
  6928. return SmartArray;
  6929. }());
  6930. BABYLON.SmartArray = SmartArray;
  6931. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6932. __extends(SmartArrayNoDuplicate, _super);
  6933. function SmartArrayNoDuplicate() {
  6934. var _this = _super !== null && _super.apply(this, arguments) || this;
  6935. _this._duplicateId = 0;
  6936. return _this;
  6937. }
  6938. SmartArrayNoDuplicate.prototype.push = function (value) {
  6939. _super.prototype.push.call(this, value);
  6940. if (!value.__smartArrayFlags) {
  6941. value.__smartArrayFlags = {};
  6942. }
  6943. value.__smartArrayFlags[this._id] = this._duplicateId;
  6944. };
  6945. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6946. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6947. return false;
  6948. }
  6949. this.push(value);
  6950. return true;
  6951. };
  6952. SmartArrayNoDuplicate.prototype.reset = function () {
  6953. _super.prototype.reset.call(this);
  6954. this._duplicateId++;
  6955. };
  6956. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6957. if (array.length === 0) {
  6958. return;
  6959. }
  6960. if (this.length + array.length > this.data.length) {
  6961. this.data.length = (this.length + array.length) * 2;
  6962. }
  6963. for (var index = 0; index < array.length; index++) {
  6964. var item = (array.data || array)[index];
  6965. this.pushNoDuplicate(item);
  6966. }
  6967. };
  6968. return SmartArrayNoDuplicate;
  6969. }(SmartArray));
  6970. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6971. })(BABYLON || (BABYLON = {}));
  6972. //# sourceMappingURL=babylon.smartArray.js.map
  6973. var BABYLON;
  6974. (function (BABYLON) {
  6975. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6976. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6977. var LoadFileError = /** @class */ (function (_super) {
  6978. __extends(LoadFileError, _super);
  6979. function LoadFileError(message, request) {
  6980. var _this = _super.call(this, message) || this;
  6981. _this.request = request;
  6982. _this.name = "LoadFileError";
  6983. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6984. return _this;
  6985. }
  6986. // Polyfill for Object.setPrototypeOf if necessary.
  6987. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6988. return LoadFileError;
  6989. }(Error));
  6990. BABYLON.LoadFileError = LoadFileError;
  6991. var RetryStrategy = /** @class */ (function () {
  6992. function RetryStrategy() {
  6993. }
  6994. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6995. if (maxRetries === void 0) { maxRetries = 3; }
  6996. if (baseInterval === void 0) { baseInterval = 500; }
  6997. return function (url, request, retryIndex) {
  6998. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6999. return -1;
  7000. }
  7001. return Math.pow(2, retryIndex) * baseInterval;
  7002. };
  7003. };
  7004. return RetryStrategy;
  7005. }());
  7006. BABYLON.RetryStrategy = RetryStrategy;
  7007. // Screenshots
  7008. var screenshotCanvas;
  7009. var cloneValue = function (source, destinationObject) {
  7010. if (!source)
  7011. return null;
  7012. if (source instanceof BABYLON.Mesh) {
  7013. return null;
  7014. }
  7015. if (source instanceof BABYLON.SubMesh) {
  7016. return source.clone(destinationObject);
  7017. }
  7018. else if (source.clone) {
  7019. return source.clone();
  7020. }
  7021. return null;
  7022. };
  7023. var Tools = /** @class */ (function () {
  7024. function Tools() {
  7025. }
  7026. /**
  7027. * Interpolates between a and b via alpha
  7028. * @param a The lower value (returned when alpha = 0)
  7029. * @param b The upper value (returned when alpha = 1)
  7030. * @param alpha The interpolation-factor
  7031. * @return The mixed value
  7032. */
  7033. Tools.Mix = function (a, b, alpha) {
  7034. return a * (1 - alpha) + b * alpha;
  7035. };
  7036. Tools.Instantiate = function (className) {
  7037. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7038. return Tools.RegisteredExternalClasses[className];
  7039. }
  7040. var arr = className.split(".");
  7041. var fn = (window || this);
  7042. for (var i = 0, len = arr.length; i < len; i++) {
  7043. fn = fn[arr[i]];
  7044. }
  7045. if (typeof fn !== "function") {
  7046. return null;
  7047. }
  7048. return fn;
  7049. };
  7050. /**
  7051. * Provides a slice function that will work even on IE
  7052. * @param data defines the array to slice
  7053. * @returns the new sliced array
  7054. */
  7055. Tools.Slice = function (data) {
  7056. if (data.slice) {
  7057. return data.slice();
  7058. }
  7059. return Array.prototype.slice.call(data);
  7060. };
  7061. Tools.SetImmediate = function (action) {
  7062. if (window.setImmediate) {
  7063. window.setImmediate(action);
  7064. }
  7065. else {
  7066. setTimeout(action, 1);
  7067. }
  7068. };
  7069. Tools.IsExponentOfTwo = function (value) {
  7070. var count = 1;
  7071. do {
  7072. count *= 2;
  7073. } while (count < value);
  7074. return count === value;
  7075. };
  7076. /**
  7077. * Find the next highest power of two.
  7078. * @param x Number to start search from.
  7079. * @return Next highest power of two.
  7080. */
  7081. Tools.CeilingPOT = function (x) {
  7082. x--;
  7083. x |= x >> 1;
  7084. x |= x >> 2;
  7085. x |= x >> 4;
  7086. x |= x >> 8;
  7087. x |= x >> 16;
  7088. x++;
  7089. return x;
  7090. };
  7091. /**
  7092. * Find the next lowest power of two.
  7093. * @param x Number to start search from.
  7094. * @return Next lowest power of two.
  7095. */
  7096. Tools.FloorPOT = function (x) {
  7097. x = x | (x >> 1);
  7098. x = x | (x >> 2);
  7099. x = x | (x >> 4);
  7100. x = x | (x >> 8);
  7101. x = x | (x >> 16);
  7102. return x - (x >> 1);
  7103. };
  7104. /**
  7105. * Find the nearest power of two.
  7106. * @param x Number to start search from.
  7107. * @return Next nearest power of two.
  7108. */
  7109. Tools.NearestPOT = function (x) {
  7110. var c = Tools.CeilingPOT(x);
  7111. var f = Tools.FloorPOT(x);
  7112. return (c - x) > (x - f) ? f : c;
  7113. };
  7114. Tools.GetExponentOfTwo = function (value, max, mode) {
  7115. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7116. var pot;
  7117. switch (mode) {
  7118. case BABYLON.Engine.SCALEMODE_FLOOR:
  7119. pot = Tools.FloorPOT(value);
  7120. break;
  7121. case BABYLON.Engine.SCALEMODE_NEAREST:
  7122. pot = Tools.NearestPOT(value);
  7123. break;
  7124. case BABYLON.Engine.SCALEMODE_CEILING:
  7125. default:
  7126. pot = Tools.CeilingPOT(value);
  7127. break;
  7128. }
  7129. return Math.min(pot, max);
  7130. };
  7131. Tools.GetFilename = function (path) {
  7132. var index = path.lastIndexOf("/");
  7133. if (index < 0)
  7134. return path;
  7135. return path.substring(index + 1);
  7136. };
  7137. /**
  7138. * Extracts the "folder" part of a path (everything before the filename).
  7139. * @param uri The URI to extract the info from
  7140. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7141. * @returns The "folder" part of the path
  7142. */
  7143. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7144. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7145. var index = uri.lastIndexOf("/");
  7146. if (index < 0) {
  7147. if (returnUnchangedIfNoSlash) {
  7148. return uri;
  7149. }
  7150. return "";
  7151. }
  7152. return uri.substring(0, index + 1);
  7153. };
  7154. Tools.GetDOMTextContent = function (element) {
  7155. var result = "";
  7156. var child = element.firstChild;
  7157. while (child) {
  7158. if (child.nodeType === 3) {
  7159. result += child.textContent;
  7160. }
  7161. child = child.nextSibling;
  7162. }
  7163. return result;
  7164. };
  7165. Tools.ToDegrees = function (angle) {
  7166. return angle * 180 / Math.PI;
  7167. };
  7168. Tools.ToRadians = function (angle) {
  7169. return angle * Math.PI / 180;
  7170. };
  7171. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7172. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7173. var output = "";
  7174. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7175. var i = 0;
  7176. var bytes = new Uint8Array(buffer);
  7177. while (i < bytes.length) {
  7178. chr1 = bytes[i++];
  7179. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7180. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7181. enc1 = chr1 >> 2;
  7182. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7183. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7184. enc4 = chr3 & 63;
  7185. if (isNaN(chr2)) {
  7186. enc3 = enc4 = 64;
  7187. }
  7188. else if (isNaN(chr3)) {
  7189. enc4 = 64;
  7190. }
  7191. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7192. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7193. }
  7194. return "data:image/png;base64," + output;
  7195. };
  7196. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7197. if (bias === void 0) { bias = null; }
  7198. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7199. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7200. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7201. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7202. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7203. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7204. }
  7205. if (bias) {
  7206. minimum.x -= minimum.x * bias.x + bias.y;
  7207. minimum.y -= minimum.y * bias.x + bias.y;
  7208. minimum.z -= minimum.z * bias.x + bias.y;
  7209. maximum.x += maximum.x * bias.x + bias.y;
  7210. maximum.y += maximum.y * bias.x + bias.y;
  7211. maximum.z += maximum.z * bias.x + bias.y;
  7212. }
  7213. return {
  7214. minimum: minimum,
  7215. maximum: maximum
  7216. };
  7217. };
  7218. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7219. if (bias === void 0) { bias = null; }
  7220. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7221. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7222. if (!stride) {
  7223. stride = 3;
  7224. }
  7225. for (var index = start; index < start + count; index++) {
  7226. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7227. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7228. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7229. }
  7230. if (bias) {
  7231. minimum.x -= minimum.x * bias.x + bias.y;
  7232. minimum.y -= minimum.y * bias.x + bias.y;
  7233. minimum.z -= minimum.z * bias.x + bias.y;
  7234. maximum.x += maximum.x * bias.x + bias.y;
  7235. maximum.y += maximum.y * bias.x + bias.y;
  7236. maximum.z += maximum.z * bias.x + bias.y;
  7237. }
  7238. return {
  7239. minimum: minimum,
  7240. maximum: maximum
  7241. };
  7242. };
  7243. Tools.Vector2ArrayFeeder = function (array) {
  7244. return function (index) {
  7245. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7246. var length = isFloatArray ? array.length / 2 : array.length;
  7247. if (index >= length) {
  7248. return null;
  7249. }
  7250. if (isFloatArray) {
  7251. var fa = array;
  7252. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7253. }
  7254. var a = array;
  7255. return a[index];
  7256. };
  7257. };
  7258. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7259. if (bias === void 0) { bias = null; }
  7260. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7261. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7262. var i = 0;
  7263. var cur = feeder(i++);
  7264. while (cur) {
  7265. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7266. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7267. cur = feeder(i++);
  7268. }
  7269. if (bias) {
  7270. minimum.x -= minimum.x * bias.x + bias.y;
  7271. minimum.y -= minimum.y * bias.x + bias.y;
  7272. maximum.x += maximum.x * bias.x + bias.y;
  7273. maximum.y += maximum.y * bias.x + bias.y;
  7274. }
  7275. return {
  7276. minimum: minimum,
  7277. maximum: maximum
  7278. };
  7279. };
  7280. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7281. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7282. return null;
  7283. return Array.isArray(obj) ? obj : [obj];
  7284. };
  7285. // Misc.
  7286. Tools.GetPointerPrefix = function () {
  7287. var eventPrefix = "pointer";
  7288. // Check if pointer events are supported
  7289. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7290. eventPrefix = "mouse";
  7291. }
  7292. return eventPrefix;
  7293. };
  7294. /**
  7295. * @param func - the function to be called
  7296. * @param requester - the object that will request the next frame. Falls back to window.
  7297. */
  7298. Tools.QueueNewFrame = function (func, requester) {
  7299. if (!Tools.IsWindowObjectExist()) {
  7300. return setTimeout(func, 16);
  7301. }
  7302. if (!requester) {
  7303. requester = window;
  7304. }
  7305. if (requester.requestAnimationFrame) {
  7306. return requester.requestAnimationFrame(func);
  7307. }
  7308. else if (requester.msRequestAnimationFrame) {
  7309. return requester.msRequestAnimationFrame(func);
  7310. }
  7311. else if (requester.webkitRequestAnimationFrame) {
  7312. return requester.webkitRequestAnimationFrame(func);
  7313. }
  7314. else if (requester.mozRequestAnimationFrame) {
  7315. return requester.mozRequestAnimationFrame(func);
  7316. }
  7317. else if (requester.oRequestAnimationFrame) {
  7318. return requester.oRequestAnimationFrame(func);
  7319. }
  7320. else {
  7321. return window.setTimeout(func, 16);
  7322. }
  7323. };
  7324. Tools.RequestFullscreen = function (element) {
  7325. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7326. if (!requestFunction)
  7327. return;
  7328. requestFunction.call(element);
  7329. };
  7330. Tools.ExitFullscreen = function () {
  7331. if (document.exitFullscreen) {
  7332. document.exitFullscreen();
  7333. }
  7334. else if (document.mozCancelFullScreen) {
  7335. document.mozCancelFullScreen();
  7336. }
  7337. else if (document.webkitCancelFullScreen) {
  7338. document.webkitCancelFullScreen();
  7339. }
  7340. else if (document.msCancelFullScreen) {
  7341. document.msCancelFullScreen();
  7342. }
  7343. };
  7344. Tools.SetCorsBehavior = function (url, element) {
  7345. if (url && url.indexOf("data:") === 0) {
  7346. return;
  7347. }
  7348. if (Tools.CorsBehavior) {
  7349. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7350. element.crossOrigin = Tools.CorsBehavior;
  7351. }
  7352. else {
  7353. var result = Tools.CorsBehavior(url);
  7354. if (result) {
  7355. element.crossOrigin = result;
  7356. }
  7357. }
  7358. }
  7359. };
  7360. // External files
  7361. Tools.CleanUrl = function (url) {
  7362. url = url.replace(/#/mg, "%23");
  7363. return url;
  7364. };
  7365. Tools.LoadImage = function (url, onLoad, onError, database) {
  7366. if (url instanceof ArrayBuffer) {
  7367. url = Tools.EncodeArrayBufferTobase64(url);
  7368. }
  7369. url = Tools.CleanUrl(url);
  7370. url = Tools.PreprocessUrl(url);
  7371. var img = new Image();
  7372. Tools.SetCorsBehavior(url, img);
  7373. img.onload = function () {
  7374. onLoad(img);
  7375. };
  7376. img.onerror = function (err) {
  7377. Tools.Error("Error while trying to load image: " + url);
  7378. if (onError) {
  7379. onError("Error while trying to load image: " + url, err);
  7380. }
  7381. };
  7382. var noIndexedDB = function () {
  7383. img.src = url;
  7384. };
  7385. var loadFromIndexedDB = function () {
  7386. if (database) {
  7387. database.loadImageFromDB(url, img);
  7388. }
  7389. };
  7390. //ANY database to do!
  7391. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7392. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7393. }
  7394. else {
  7395. if (url.indexOf("file:") !== -1) {
  7396. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7397. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7398. try {
  7399. var blobURL;
  7400. try {
  7401. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7402. }
  7403. catch (ex) {
  7404. // Chrome doesn't support oneTimeOnly parameter
  7405. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7406. }
  7407. img.src = blobURL;
  7408. }
  7409. catch (e) {
  7410. img.src = "";
  7411. }
  7412. return img;
  7413. }
  7414. }
  7415. noIndexedDB();
  7416. }
  7417. return img;
  7418. };
  7419. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7420. url = Tools.CleanUrl(url);
  7421. url = Tools.PreprocessUrl(url);
  7422. // If file and file input are set
  7423. if (url.indexOf("file:") !== -1) {
  7424. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7425. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7426. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7427. }
  7428. }
  7429. var loadUrl = Tools.BaseUrl + url;
  7430. var aborted = false;
  7431. var fileRequest = {
  7432. onCompleteObservable: new BABYLON.Observable(),
  7433. abort: function () { return aborted = true; },
  7434. };
  7435. var requestFile = function () {
  7436. var request = new XMLHttpRequest();
  7437. var retryHandle = null;
  7438. fileRequest.abort = function () {
  7439. aborted = true;
  7440. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7441. request.abort();
  7442. }
  7443. if (retryHandle !== null) {
  7444. clearTimeout(retryHandle);
  7445. retryHandle = null;
  7446. }
  7447. };
  7448. var retryLoop = function (retryIndex) {
  7449. request.open('GET', loadUrl, true);
  7450. if (useArrayBuffer) {
  7451. request.responseType = "arraybuffer";
  7452. }
  7453. if (onProgress) {
  7454. request.addEventListener("progress", onProgress);
  7455. }
  7456. var onLoadEnd = function () {
  7457. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7458. };
  7459. request.addEventListener("loadend", onLoadEnd);
  7460. var onReadyStateChange = function () {
  7461. if (aborted) {
  7462. return;
  7463. }
  7464. // In case of undefined state in some browsers.
  7465. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7466. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7467. request.removeEventListener("readystatechange", onReadyStateChange);
  7468. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7469. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7470. return;
  7471. }
  7472. var retryStrategy = Tools.DefaultRetryStrategy;
  7473. if (retryStrategy) {
  7474. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7475. if (waitTime !== -1) {
  7476. // Prevent the request from completing for retry.
  7477. request.removeEventListener("loadend", onLoadEnd);
  7478. request = new XMLHttpRequest();
  7479. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7480. return;
  7481. }
  7482. }
  7483. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7484. if (onError) {
  7485. onError(request, e);
  7486. }
  7487. else {
  7488. throw e;
  7489. }
  7490. }
  7491. };
  7492. request.addEventListener("readystatechange", onReadyStateChange);
  7493. request.send();
  7494. };
  7495. retryLoop(0);
  7496. };
  7497. // Caching all files
  7498. if (database && database.enableSceneOffline) {
  7499. var noIndexedDB_1 = function () {
  7500. if (!aborted) {
  7501. requestFile();
  7502. }
  7503. };
  7504. var loadFromIndexedDB = function () {
  7505. // TODO: database needs to support aborting and should return a IFileRequest
  7506. if (aborted) {
  7507. return;
  7508. }
  7509. if (database) {
  7510. database.loadFileFromDB(url, function (data) {
  7511. if (!aborted) {
  7512. onSuccess(data);
  7513. }
  7514. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7515. }, onProgress ? function (event) {
  7516. if (!aborted) {
  7517. onProgress(event);
  7518. }
  7519. } : undefined, noIndexedDB_1, useArrayBuffer);
  7520. }
  7521. };
  7522. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7523. }
  7524. else {
  7525. requestFile();
  7526. }
  7527. return fileRequest;
  7528. };
  7529. /**
  7530. * Load a script (identified by an url). When the url returns, the
  7531. * content of this file is added into a new script element, attached to the DOM (body element)
  7532. */
  7533. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7534. var head = document.getElementsByTagName('head')[0];
  7535. var script = document.createElement('script');
  7536. script.type = 'text/javascript';
  7537. script.src = scriptUrl;
  7538. script.onload = function () {
  7539. if (onSuccess) {
  7540. onSuccess();
  7541. }
  7542. };
  7543. script.onerror = function (e) {
  7544. if (onError) {
  7545. onError("Unable to load script", e);
  7546. }
  7547. };
  7548. head.appendChild(script);
  7549. };
  7550. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7551. var reader = new FileReader();
  7552. var request = {
  7553. onCompleteObservable: new BABYLON.Observable(),
  7554. abort: function () { return reader.abort(); },
  7555. };
  7556. reader.onloadend = function (e) {
  7557. request.onCompleteObservable.notifyObservers(request);
  7558. };
  7559. reader.onload = function (e) {
  7560. //target doesn't have result from ts 1.3
  7561. callback(e.target['result']);
  7562. };
  7563. reader.onprogress = progressCallback;
  7564. reader.readAsDataURL(fileToLoad);
  7565. return request;
  7566. };
  7567. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7568. var reader = new FileReader();
  7569. var request = {
  7570. onCompleteObservable: new BABYLON.Observable(),
  7571. abort: function () { return reader.abort(); },
  7572. };
  7573. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7574. reader.onerror = function (e) {
  7575. Tools.Log("Error while reading file: " + fileToLoad.name);
  7576. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7577. };
  7578. reader.onload = function (e) {
  7579. //target doesn't have result from ts 1.3
  7580. callback(e.target['result']);
  7581. };
  7582. if (progressCallBack) {
  7583. reader.onprogress = progressCallBack;
  7584. }
  7585. if (!useArrayBuffer) {
  7586. // Asynchronous read
  7587. reader.readAsText(fileToLoad);
  7588. }
  7589. else {
  7590. reader.readAsArrayBuffer(fileToLoad);
  7591. }
  7592. return request;
  7593. };
  7594. //returns a downloadable url to a file content.
  7595. Tools.FileAsURL = function (content) {
  7596. var fileBlob = new Blob([content]);
  7597. var url = window.URL || window.webkitURL;
  7598. var link = url.createObjectURL(fileBlob);
  7599. return link;
  7600. };
  7601. // Misc.
  7602. Tools.Format = function (value, decimals) {
  7603. if (decimals === void 0) { decimals = 2; }
  7604. return value.toFixed(decimals);
  7605. };
  7606. Tools.CheckExtends = function (v, min, max) {
  7607. if (v.x < min.x)
  7608. min.x = v.x;
  7609. if (v.y < min.y)
  7610. min.y = v.y;
  7611. if (v.z < min.z)
  7612. min.z = v.z;
  7613. if (v.x > max.x)
  7614. max.x = v.x;
  7615. if (v.y > max.y)
  7616. max.y = v.y;
  7617. if (v.z > max.z)
  7618. max.z = v.z;
  7619. };
  7620. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7621. for (var prop in source) {
  7622. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7623. continue;
  7624. }
  7625. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7626. continue;
  7627. }
  7628. var sourceValue = source[prop];
  7629. var typeOfSourceValue = typeof sourceValue;
  7630. if (typeOfSourceValue === "function") {
  7631. continue;
  7632. }
  7633. if (typeOfSourceValue === "object") {
  7634. if (sourceValue instanceof Array) {
  7635. destination[prop] = [];
  7636. if (sourceValue.length > 0) {
  7637. if (typeof sourceValue[0] == "object") {
  7638. for (var index = 0; index < sourceValue.length; index++) {
  7639. var clonedValue = cloneValue(sourceValue[index], destination);
  7640. if (destination[prop].indexOf(clonedValue) === -1) {
  7641. destination[prop].push(clonedValue);
  7642. }
  7643. }
  7644. }
  7645. else {
  7646. destination[prop] = sourceValue.slice(0);
  7647. }
  7648. }
  7649. }
  7650. else {
  7651. destination[prop] = cloneValue(sourceValue, destination);
  7652. }
  7653. }
  7654. else {
  7655. destination[prop] = sourceValue;
  7656. }
  7657. }
  7658. };
  7659. Tools.IsEmpty = function (obj) {
  7660. for (var i in obj) {
  7661. if (obj.hasOwnProperty(i)) {
  7662. return false;
  7663. }
  7664. }
  7665. return true;
  7666. };
  7667. Tools.RegisterTopRootEvents = function (events) {
  7668. for (var index = 0; index < events.length; index++) {
  7669. var event = events[index];
  7670. window.addEventListener(event.name, event.handler, false);
  7671. try {
  7672. if (window.parent) {
  7673. window.parent.addEventListener(event.name, event.handler, false);
  7674. }
  7675. }
  7676. catch (e) {
  7677. // Silently fails...
  7678. }
  7679. }
  7680. };
  7681. Tools.UnregisterTopRootEvents = function (events) {
  7682. for (var index = 0; index < events.length; index++) {
  7683. var event = events[index];
  7684. window.removeEventListener(event.name, event.handler);
  7685. try {
  7686. if (window.parent) {
  7687. window.parent.removeEventListener(event.name, event.handler);
  7688. }
  7689. }
  7690. catch (e) {
  7691. // Silently fails...
  7692. }
  7693. }
  7694. };
  7695. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7696. if (mimeType === void 0) { mimeType = "image/png"; }
  7697. // Read the contents of the framebuffer
  7698. var numberOfChannelsByLine = width * 4;
  7699. var halfHeight = height / 2;
  7700. //Reading datas from WebGL
  7701. var data = engine.readPixels(0, 0, width, height);
  7702. //To flip image on Y axis.
  7703. for (var i = 0; i < halfHeight; i++) {
  7704. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7705. var currentCell = j + i * numberOfChannelsByLine;
  7706. var targetLine = height - i - 1;
  7707. var targetCell = j + targetLine * numberOfChannelsByLine;
  7708. var temp = data[currentCell];
  7709. data[currentCell] = data[targetCell];
  7710. data[targetCell] = temp;
  7711. }
  7712. }
  7713. // Create a 2D canvas to store the result
  7714. if (!screenshotCanvas) {
  7715. screenshotCanvas = document.createElement('canvas');
  7716. }
  7717. screenshotCanvas.width = width;
  7718. screenshotCanvas.height = height;
  7719. var context = screenshotCanvas.getContext('2d');
  7720. if (context) {
  7721. // Copy the pixels to a 2D canvas
  7722. var imageData = context.createImageData(width, height);
  7723. var castData = (imageData.data);
  7724. castData.set(data);
  7725. context.putImageData(imageData, 0, 0);
  7726. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7727. }
  7728. };
  7729. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7730. if (mimeType === void 0) { mimeType = "image/png"; }
  7731. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7732. if (successCallback) {
  7733. successCallback(base64Image);
  7734. }
  7735. else {
  7736. // We need HTMLCanvasElement.toBlob for HD screenshots
  7737. if (!screenshotCanvas.toBlob) {
  7738. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7739. screenshotCanvas.toBlob = function (callback, type, quality) {
  7740. var _this = this;
  7741. setTimeout(function () {
  7742. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7743. for (var i = 0; i < len; i++) {
  7744. arr[i] = binStr.charCodeAt(i);
  7745. }
  7746. callback(new Blob([arr], { type: type || 'image/png' }));
  7747. });
  7748. };
  7749. }
  7750. screenshotCanvas.toBlob(function (blob) {
  7751. var url = URL.createObjectURL(blob);
  7752. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7753. if (("download" in document.createElement("a"))) {
  7754. var a = window.document.createElement("a");
  7755. a.href = url;
  7756. if (fileName) {
  7757. a.setAttribute("download", fileName);
  7758. }
  7759. else {
  7760. var date = new Date();
  7761. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7762. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7763. }
  7764. window.document.body.appendChild(a);
  7765. a.addEventListener("click", function () {
  7766. if (a.parentElement) {
  7767. a.parentElement.removeChild(a);
  7768. }
  7769. });
  7770. a.click();
  7771. }
  7772. else {
  7773. var newWindow = window.open("");
  7774. if (!newWindow)
  7775. return;
  7776. var img = newWindow.document.createElement("img");
  7777. img.onload = function () {
  7778. // no longer need to read the blob so it's revoked
  7779. URL.revokeObjectURL(url);
  7780. };
  7781. img.src = url;
  7782. newWindow.document.body.appendChild(img);
  7783. }
  7784. });
  7785. }
  7786. };
  7787. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7788. if (mimeType === void 0) { mimeType = "image/png"; }
  7789. var width;
  7790. var height;
  7791. // If a precision value is specified
  7792. if (size.precision) {
  7793. width = Math.round(engine.getRenderWidth() * size.precision);
  7794. height = Math.round(width / engine.getAspectRatio(camera));
  7795. }
  7796. else if (size.width && size.height) {
  7797. width = size.width;
  7798. height = size.height;
  7799. }
  7800. else if (size.width && !size.height) {
  7801. width = size.width;
  7802. height = Math.round(width / engine.getAspectRatio(camera));
  7803. }
  7804. else if (size.height && !size.width) {
  7805. height = size.height;
  7806. width = Math.round(height * engine.getAspectRatio(camera));
  7807. }
  7808. else if (!isNaN(size)) {
  7809. height = size;
  7810. width = size;
  7811. }
  7812. else {
  7813. Tools.Error("Invalid 'size' parameter !");
  7814. return;
  7815. }
  7816. if (!screenshotCanvas) {
  7817. screenshotCanvas = document.createElement('canvas');
  7818. }
  7819. screenshotCanvas.width = width;
  7820. screenshotCanvas.height = height;
  7821. var renderContext = screenshotCanvas.getContext("2d");
  7822. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7823. var newWidth = width;
  7824. var newHeight = newWidth / ratio;
  7825. if (newHeight > height) {
  7826. newHeight = height;
  7827. newWidth = newHeight * ratio;
  7828. }
  7829. var offsetX = Math.max(0, width - newWidth) / 2;
  7830. var offsetY = Math.max(0, height - newHeight) / 2;
  7831. var renderingCanvas = engine.getRenderingCanvas();
  7832. if (renderContext && renderingCanvas) {
  7833. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7834. }
  7835. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7836. };
  7837. /**
  7838. * Generates an image screenshot from the specified camera.
  7839. *
  7840. * @param engine The engine to use for rendering
  7841. * @param camera The camera to use for rendering
  7842. * @param size This parameter can be set to a single number or to an object with the
  7843. * following (optional) properties: precision, width, height. If a single number is passed,
  7844. * it will be used for both width and height. If an object is passed, the screenshot size
  7845. * will be derived from the parameters. The precision property is a multiplier allowing
  7846. * rendering at a higher or lower resolution.
  7847. * @param successCallback The callback receives a single parameter which contains the
  7848. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7849. * src parameter of an <img> to display it.
  7850. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7851. * Check your browser for supported MIME types.
  7852. * @param samples Texture samples (default: 1)
  7853. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7854. * @param fileName A name for for the downloaded file.
  7855. * @constructor
  7856. */
  7857. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7858. if (mimeType === void 0) { mimeType = "image/png"; }
  7859. if (samples === void 0) { samples = 1; }
  7860. if (antialiasing === void 0) { antialiasing = false; }
  7861. var width;
  7862. var height;
  7863. //If a precision value is specified
  7864. if (size.precision) {
  7865. width = Math.round(engine.getRenderWidth() * size.precision);
  7866. height = Math.round(width / engine.getAspectRatio(camera));
  7867. size = { width: width, height: height };
  7868. }
  7869. else if (size.width && size.height) {
  7870. width = size.width;
  7871. height = size.height;
  7872. }
  7873. else if (size.width && !size.height) {
  7874. width = size.width;
  7875. height = Math.round(width / engine.getAspectRatio(camera));
  7876. size = { width: width, height: height };
  7877. }
  7878. else if (size.height && !size.width) {
  7879. height = size.height;
  7880. width = Math.round(height * engine.getAspectRatio(camera));
  7881. size = { width: width, height: height };
  7882. }
  7883. else if (!isNaN(size)) {
  7884. height = size;
  7885. width = size;
  7886. }
  7887. else {
  7888. Tools.Error("Invalid 'size' parameter !");
  7889. return;
  7890. }
  7891. var scene = camera.getScene();
  7892. var previousCamera = null;
  7893. if (scene.activeCamera !== camera) {
  7894. previousCamera = scene.activeCamera;
  7895. scene.activeCamera = camera;
  7896. }
  7897. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7898. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7899. texture.renderList = null;
  7900. texture.samples = samples;
  7901. if (antialiasing) {
  7902. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7903. }
  7904. texture.onAfterRenderObservable.add(function () {
  7905. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7906. });
  7907. scene.incrementRenderId();
  7908. scene.resetCachedMaterial();
  7909. texture.render(true);
  7910. texture.dispose();
  7911. if (previousCamera) {
  7912. scene.activeCamera = previousCamera;
  7913. }
  7914. camera.getProjectionMatrix(true); // Force cache refresh;
  7915. };
  7916. // XHR response validator for local file scenario
  7917. Tools.ValidateXHRData = function (xhr, dataType) {
  7918. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7919. if (dataType === void 0) { dataType = 7; }
  7920. try {
  7921. if (dataType & 1) {
  7922. if (xhr.responseText && xhr.responseText.length > 0) {
  7923. return true;
  7924. }
  7925. else if (dataType === 1) {
  7926. return false;
  7927. }
  7928. }
  7929. if (dataType & 2) {
  7930. // Check header width and height since there is no "TGA" magic number
  7931. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7932. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7933. return true;
  7934. }
  7935. else if (dataType === 2) {
  7936. return false;
  7937. }
  7938. }
  7939. if (dataType & 4) {
  7940. // Check for the "DDS" magic number
  7941. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7942. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7943. return true;
  7944. }
  7945. else {
  7946. return false;
  7947. }
  7948. }
  7949. }
  7950. catch (e) {
  7951. // Global protection
  7952. }
  7953. return false;
  7954. };
  7955. /**
  7956. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7957. * Be aware Math.random() could cause collisions, but:
  7958. * "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"
  7959. */
  7960. Tools.RandomId = function () {
  7961. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7962. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7963. return v.toString(16);
  7964. });
  7965. };
  7966. /**
  7967. * Test if the given uri is a base64 string.
  7968. * @param uri The uri to test
  7969. * @return True if the uri is a base64 string or false otherwise.
  7970. */
  7971. Tools.IsBase64 = function (uri) {
  7972. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  7973. };
  7974. /**
  7975. * Decode the given base64 uri.
  7976. * @param uri The uri to decode
  7977. * @return The decoded base64 data.
  7978. */
  7979. Tools.DecodeBase64 = function (uri) {
  7980. var decodedString = atob(uri.split(",")[1]);
  7981. var bufferLength = decodedString.length;
  7982. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  7983. for (var i = 0; i < bufferLength; i++) {
  7984. bufferView[i] = decodedString.charCodeAt(i);
  7985. }
  7986. return bufferView.buffer;
  7987. };
  7988. Object.defineProperty(Tools, "NoneLogLevel", {
  7989. get: function () {
  7990. return Tools._NoneLogLevel;
  7991. },
  7992. enumerable: true,
  7993. configurable: true
  7994. });
  7995. Object.defineProperty(Tools, "MessageLogLevel", {
  7996. get: function () {
  7997. return Tools._MessageLogLevel;
  7998. },
  7999. enumerable: true,
  8000. configurable: true
  8001. });
  8002. Object.defineProperty(Tools, "WarningLogLevel", {
  8003. get: function () {
  8004. return Tools._WarningLogLevel;
  8005. },
  8006. enumerable: true,
  8007. configurable: true
  8008. });
  8009. Object.defineProperty(Tools, "ErrorLogLevel", {
  8010. get: function () {
  8011. return Tools._ErrorLogLevel;
  8012. },
  8013. enumerable: true,
  8014. configurable: true
  8015. });
  8016. Object.defineProperty(Tools, "AllLogLevel", {
  8017. get: function () {
  8018. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8019. },
  8020. enumerable: true,
  8021. configurable: true
  8022. });
  8023. Tools._AddLogEntry = function (entry) {
  8024. Tools._LogCache = entry + Tools._LogCache;
  8025. if (Tools.OnNewCacheEntry) {
  8026. Tools.OnNewCacheEntry(entry);
  8027. }
  8028. };
  8029. Tools._FormatMessage = function (message) {
  8030. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8031. var date = new Date();
  8032. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8033. };
  8034. Tools._LogDisabled = function (message) {
  8035. // nothing to do
  8036. };
  8037. Tools._LogEnabled = function (message) {
  8038. var formattedMessage = Tools._FormatMessage(message);
  8039. console.log("BJS - " + formattedMessage);
  8040. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8041. Tools._AddLogEntry(entry);
  8042. };
  8043. Tools._WarnDisabled = function (message) {
  8044. // nothing to do
  8045. };
  8046. Tools._WarnEnabled = function (message) {
  8047. var formattedMessage = Tools._FormatMessage(message);
  8048. console.warn("BJS - " + formattedMessage);
  8049. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8050. Tools._AddLogEntry(entry);
  8051. };
  8052. Tools._ErrorDisabled = function (message) {
  8053. // nothing to do
  8054. };
  8055. Tools._ErrorEnabled = function (message) {
  8056. Tools.errorsCount++;
  8057. var formattedMessage = Tools._FormatMessage(message);
  8058. console.error("BJS - " + formattedMessage);
  8059. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8060. Tools._AddLogEntry(entry);
  8061. };
  8062. Object.defineProperty(Tools, "LogCache", {
  8063. get: function () {
  8064. return Tools._LogCache;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. Tools.ClearLogCache = function () {
  8070. Tools._LogCache = "";
  8071. Tools.errorsCount = 0;
  8072. };
  8073. Object.defineProperty(Tools, "LogLevels", {
  8074. set: function (level) {
  8075. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8076. Tools.Log = Tools._LogEnabled;
  8077. }
  8078. else {
  8079. Tools.Log = Tools._LogDisabled;
  8080. }
  8081. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8082. Tools.Warn = Tools._WarnEnabled;
  8083. }
  8084. else {
  8085. Tools.Warn = Tools._WarnDisabled;
  8086. }
  8087. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8088. Tools.Error = Tools._ErrorEnabled;
  8089. }
  8090. else {
  8091. Tools.Error = Tools._ErrorDisabled;
  8092. }
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. Tools.IsWindowObjectExist = function () {
  8098. return (typeof window) !== "undefined";
  8099. };
  8100. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8101. get: function () {
  8102. return Tools._PerformanceNoneLogLevel;
  8103. },
  8104. enumerable: true,
  8105. configurable: true
  8106. });
  8107. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8108. get: function () {
  8109. return Tools._PerformanceUserMarkLogLevel;
  8110. },
  8111. enumerable: true,
  8112. configurable: true
  8113. });
  8114. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8115. get: function () {
  8116. return Tools._PerformanceConsoleLogLevel;
  8117. },
  8118. enumerable: true,
  8119. configurable: true
  8120. });
  8121. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8122. set: function (level) {
  8123. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8124. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8125. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8126. return;
  8127. }
  8128. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8129. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8130. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8131. return;
  8132. }
  8133. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8134. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8135. },
  8136. enumerable: true,
  8137. configurable: true
  8138. });
  8139. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8140. };
  8141. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8142. };
  8143. Tools._StartUserMark = function (counterName, condition) {
  8144. if (condition === void 0) { condition = true; }
  8145. if (!Tools._performance) {
  8146. if (!Tools.IsWindowObjectExist()) {
  8147. return;
  8148. }
  8149. Tools._performance = window.performance;
  8150. }
  8151. if (!condition || !Tools._performance.mark) {
  8152. return;
  8153. }
  8154. Tools._performance.mark(counterName + "-Begin");
  8155. };
  8156. Tools._EndUserMark = function (counterName, condition) {
  8157. if (condition === void 0) { condition = true; }
  8158. if (!condition || !Tools._performance.mark) {
  8159. return;
  8160. }
  8161. Tools._performance.mark(counterName + "-End");
  8162. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8163. };
  8164. Tools._StartPerformanceConsole = function (counterName, condition) {
  8165. if (condition === void 0) { condition = true; }
  8166. if (!condition) {
  8167. return;
  8168. }
  8169. Tools._StartUserMark(counterName, condition);
  8170. if (console.time) {
  8171. console.time(counterName);
  8172. }
  8173. };
  8174. Tools._EndPerformanceConsole = function (counterName, condition) {
  8175. if (condition === void 0) { condition = true; }
  8176. if (!condition) {
  8177. return;
  8178. }
  8179. Tools._EndUserMark(counterName, condition);
  8180. if (console.time) {
  8181. console.timeEnd(counterName);
  8182. }
  8183. };
  8184. Object.defineProperty(Tools, "Now", {
  8185. get: function () {
  8186. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8187. return window.performance.now();
  8188. }
  8189. return new Date().getTime();
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. /**
  8195. * This method will return the name of the class used to create the instance of the given object.
  8196. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8197. * @param object the object to get the class name from
  8198. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8199. */
  8200. Tools.GetClassName = function (object, isType) {
  8201. if (isType === void 0) { isType = false; }
  8202. var name = null;
  8203. if (!isType && object.getClassName) {
  8204. name = object.getClassName();
  8205. }
  8206. else {
  8207. if (object instanceof Object) {
  8208. var classObj = isType ? object : Object.getPrototypeOf(object);
  8209. name = classObj.constructor["__bjsclassName__"];
  8210. }
  8211. if (!name) {
  8212. name = typeof object;
  8213. }
  8214. }
  8215. return name;
  8216. };
  8217. Tools.First = function (array, predicate) {
  8218. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8219. var el = array_1[_i];
  8220. if (predicate(el)) {
  8221. return el;
  8222. }
  8223. }
  8224. return null;
  8225. };
  8226. /**
  8227. * This method will return the name of the full name of the class, including its owning module (if any).
  8228. * 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).
  8229. * @param object the object to get the class name from
  8230. * @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.
  8231. */
  8232. Tools.getFullClassName = function (object, isType) {
  8233. if (isType === void 0) { isType = false; }
  8234. var className = null;
  8235. var moduleName = null;
  8236. if (!isType && object.getClassName) {
  8237. className = object.getClassName();
  8238. }
  8239. else {
  8240. if (object instanceof Object) {
  8241. var classObj = isType ? object : Object.getPrototypeOf(object);
  8242. className = classObj.constructor["__bjsclassName__"];
  8243. moduleName = classObj.constructor["__bjsmoduleName__"];
  8244. }
  8245. if (!className) {
  8246. className = typeof object;
  8247. }
  8248. }
  8249. if (!className) {
  8250. return null;
  8251. }
  8252. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8253. };
  8254. /**
  8255. * 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.
  8256. * @param array
  8257. */
  8258. Tools.arrayOrStringFeeder = function (array) {
  8259. return function (index) {
  8260. if (index >= array.length) {
  8261. return null;
  8262. }
  8263. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8264. if (val && val.getHashCode) {
  8265. val = val.getHashCode();
  8266. }
  8267. if (typeof val === "string") {
  8268. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8269. }
  8270. return val;
  8271. };
  8272. };
  8273. /**
  8274. * Compute the hashCode of a stream of number
  8275. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8276. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8277. * @return the hash code computed
  8278. */
  8279. Tools.hashCodeFromStream = function (feeder) {
  8280. // Based from here: http://stackoverflow.com/a/7616484/802124
  8281. var hash = 0;
  8282. var index = 0;
  8283. var chr = feeder(index++);
  8284. while (chr != null) {
  8285. hash = ((hash << 5) - hash) + chr;
  8286. hash |= 0; // Convert to 32bit integer
  8287. chr = feeder(index++);
  8288. }
  8289. return hash;
  8290. };
  8291. Tools.BaseUrl = "";
  8292. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8293. /**
  8294. * Default behaviour for cors in the application.
  8295. * It can be a string if the expected behavior is identical in the entire app.
  8296. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8297. */
  8298. Tools.CorsBehavior = "anonymous";
  8299. Tools.UseFallbackTexture = true;
  8300. /**
  8301. * Use this object to register external classes like custom textures or material
  8302. * to allow the laoders to instantiate them
  8303. */
  8304. Tools.RegisteredExternalClasses = {};
  8305. // Used in case of a texture loading problem
  8306. 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";
  8307. Tools.PreprocessUrl = function (url) {
  8308. return url;
  8309. };
  8310. // Logs
  8311. Tools._NoneLogLevel = 0;
  8312. Tools._MessageLogLevel = 1;
  8313. Tools._WarningLogLevel = 2;
  8314. Tools._ErrorLogLevel = 4;
  8315. Tools._LogCache = "";
  8316. Tools.errorsCount = 0;
  8317. Tools.Log = Tools._LogEnabled;
  8318. Tools.Warn = Tools._WarnEnabled;
  8319. Tools.Error = Tools._ErrorEnabled;
  8320. // Performances
  8321. Tools._PerformanceNoneLogLevel = 0;
  8322. Tools._PerformanceUserMarkLogLevel = 1;
  8323. Tools._PerformanceConsoleLogLevel = 2;
  8324. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8325. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8326. return Tools;
  8327. }());
  8328. BABYLON.Tools = Tools;
  8329. /**
  8330. * This class is used to track a performance counter which is number based.
  8331. * The user has access to many properties which give statistics of different nature
  8332. *
  8333. * The implementer can track two kinds of Performance Counter: time and count
  8334. * 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.
  8335. * 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.
  8336. */
  8337. var PerfCounter = /** @class */ (function () {
  8338. function PerfCounter() {
  8339. this._startMonitoringTime = 0;
  8340. this._min = 0;
  8341. this._max = 0;
  8342. this._average = 0;
  8343. this._lastSecAverage = 0;
  8344. this._current = 0;
  8345. this._totalValueCount = 0;
  8346. this._totalAccumulated = 0;
  8347. this._lastSecAccumulated = 0;
  8348. this._lastSecTime = 0;
  8349. this._lastSecValueCount = 0;
  8350. }
  8351. Object.defineProperty(PerfCounter.prototype, "min", {
  8352. /**
  8353. * Returns the smallest value ever
  8354. */
  8355. get: function () {
  8356. return this._min;
  8357. },
  8358. enumerable: true,
  8359. configurable: true
  8360. });
  8361. Object.defineProperty(PerfCounter.prototype, "max", {
  8362. /**
  8363. * Returns the biggest value ever
  8364. */
  8365. get: function () {
  8366. return this._max;
  8367. },
  8368. enumerable: true,
  8369. configurable: true
  8370. });
  8371. Object.defineProperty(PerfCounter.prototype, "average", {
  8372. /**
  8373. * Returns the average value since the performance counter is running
  8374. */
  8375. get: function () {
  8376. return this._average;
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8382. /**
  8383. * Returns the average value of the last second the counter was monitored
  8384. */
  8385. get: function () {
  8386. return this._lastSecAverage;
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. Object.defineProperty(PerfCounter.prototype, "current", {
  8392. /**
  8393. * Returns the current value
  8394. */
  8395. get: function () {
  8396. return this._current;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(PerfCounter.prototype, "total", {
  8402. get: function () {
  8403. return this._totalAccumulated;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(PerfCounter.prototype, "count", {
  8409. get: function () {
  8410. return this._totalValueCount;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. /**
  8416. * Call this method to start monitoring a new frame.
  8417. * 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.
  8418. */
  8419. PerfCounter.prototype.fetchNewFrame = function () {
  8420. this._totalValueCount++;
  8421. this._current = 0;
  8422. this._lastSecValueCount++;
  8423. };
  8424. /**
  8425. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8426. * @param newCount the count value to add to the monitored count
  8427. * @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.
  8428. */
  8429. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8430. if (!PerfCounter.Enabled) {
  8431. return;
  8432. }
  8433. this._current += newCount;
  8434. if (fetchResult) {
  8435. this._fetchResult();
  8436. }
  8437. };
  8438. /**
  8439. * Start monitoring this performance counter
  8440. */
  8441. PerfCounter.prototype.beginMonitoring = function () {
  8442. if (!PerfCounter.Enabled) {
  8443. return;
  8444. }
  8445. this._startMonitoringTime = Tools.Now;
  8446. };
  8447. /**
  8448. * Compute the time lapsed since the previous beginMonitoring() call.
  8449. * @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
  8450. */
  8451. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8452. if (newFrame === void 0) { newFrame = true; }
  8453. if (!PerfCounter.Enabled) {
  8454. return;
  8455. }
  8456. if (newFrame) {
  8457. this.fetchNewFrame();
  8458. }
  8459. var currentTime = Tools.Now;
  8460. this._current = currentTime - this._startMonitoringTime;
  8461. if (newFrame) {
  8462. this._fetchResult();
  8463. }
  8464. };
  8465. PerfCounter.prototype._fetchResult = function () {
  8466. this._totalAccumulated += this._current;
  8467. this._lastSecAccumulated += this._current;
  8468. // Min/Max update
  8469. this._min = Math.min(this._min, this._current);
  8470. this._max = Math.max(this._max, this._current);
  8471. this._average = this._totalAccumulated / this._totalValueCount;
  8472. // Reset last sec?
  8473. var now = Tools.Now;
  8474. if ((now - this._lastSecTime) > 1000) {
  8475. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8476. this._lastSecTime = now;
  8477. this._lastSecAccumulated = 0;
  8478. this._lastSecValueCount = 0;
  8479. }
  8480. };
  8481. PerfCounter.Enabled = true;
  8482. return PerfCounter;
  8483. }());
  8484. BABYLON.PerfCounter = PerfCounter;
  8485. /**
  8486. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8487. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8488. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8489. * @param name The name of the class, case should be preserved
  8490. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8491. */
  8492. function className(name, module) {
  8493. return function (target) {
  8494. target["__bjsclassName__"] = name;
  8495. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8496. };
  8497. }
  8498. BABYLON.className = className;
  8499. /**
  8500. * An implementation of a loop for asynchronous functions.
  8501. */
  8502. var AsyncLoop = /** @class */ (function () {
  8503. /**
  8504. * Constroctor.
  8505. * @param iterations the number of iterations.
  8506. * @param _fn the function to run each iteration
  8507. * @param _successCallback the callback that will be called upon succesful execution
  8508. * @param offset starting offset.
  8509. */
  8510. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8511. if (offset === void 0) { offset = 0; }
  8512. this.iterations = iterations;
  8513. this._fn = _fn;
  8514. this._successCallback = _successCallback;
  8515. this.index = offset - 1;
  8516. this._done = false;
  8517. }
  8518. /**
  8519. * Execute the next iteration. Must be called after the last iteration was finished.
  8520. */
  8521. AsyncLoop.prototype.executeNext = function () {
  8522. if (!this._done) {
  8523. if (this.index + 1 < this.iterations) {
  8524. ++this.index;
  8525. this._fn(this);
  8526. }
  8527. else {
  8528. this.breakLoop();
  8529. }
  8530. }
  8531. };
  8532. /**
  8533. * Break the loop and run the success callback.
  8534. */
  8535. AsyncLoop.prototype.breakLoop = function () {
  8536. this._done = true;
  8537. this._successCallback();
  8538. };
  8539. /**
  8540. * Helper function
  8541. */
  8542. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8543. if (offset === void 0) { offset = 0; }
  8544. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8545. loop.executeNext();
  8546. return loop;
  8547. };
  8548. /**
  8549. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8550. * @param iterations total number of iterations
  8551. * @param syncedIterations number of synchronous iterations in each async iteration.
  8552. * @param fn the function to call each iteration.
  8553. * @param callback a success call back that will be called when iterating stops.
  8554. * @param breakFunction a break condition (optional)
  8555. * @param timeout timeout settings for the setTimeout function. default - 0.
  8556. * @constructor
  8557. */
  8558. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8559. if (timeout === void 0) { timeout = 0; }
  8560. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8561. if (breakFunction && breakFunction())
  8562. loop.breakLoop();
  8563. else {
  8564. setTimeout(function () {
  8565. for (var i = 0; i < syncedIterations; ++i) {
  8566. var iteration = (loop.index * syncedIterations) + i;
  8567. if (iteration >= iterations)
  8568. break;
  8569. fn(iteration);
  8570. if (breakFunction && breakFunction()) {
  8571. loop.breakLoop();
  8572. break;
  8573. }
  8574. }
  8575. loop.executeNext();
  8576. }, timeout);
  8577. }
  8578. }, callback);
  8579. };
  8580. return AsyncLoop;
  8581. }());
  8582. BABYLON.AsyncLoop = AsyncLoop;
  8583. })(BABYLON || (BABYLON = {}));
  8584. //# sourceMappingURL=babylon.tools.js.map
  8585. var BABYLON;
  8586. (function (BABYLON) {
  8587. var PromiseStates;
  8588. (function (PromiseStates) {
  8589. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8590. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8591. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8592. })(PromiseStates || (PromiseStates = {}));
  8593. var FulFillmentAgregator = /** @class */ (function () {
  8594. function FulFillmentAgregator() {
  8595. this.count = 0;
  8596. this.target = 0;
  8597. this.results = [];
  8598. }
  8599. return FulFillmentAgregator;
  8600. }());
  8601. var InternalPromise = /** @class */ (function () {
  8602. function InternalPromise(resolver) {
  8603. var _this = this;
  8604. this._state = PromiseStates.Pending;
  8605. this._children = new Array();
  8606. this._rejectWasConsumed = false;
  8607. if (!resolver) {
  8608. return;
  8609. }
  8610. try {
  8611. resolver(function (value) {
  8612. _this._resolve(value);
  8613. }, function (reason) {
  8614. _this._reject(reason);
  8615. });
  8616. }
  8617. catch (e) {
  8618. this._reject(e.message);
  8619. }
  8620. }
  8621. Object.defineProperty(InternalPromise.prototype, "state", {
  8622. get: function () {
  8623. return this._state;
  8624. },
  8625. enumerable: true,
  8626. configurable: true
  8627. });
  8628. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8629. get: function () {
  8630. return this._state === PromiseStates.Fulfilled;
  8631. },
  8632. enumerable: true,
  8633. configurable: true
  8634. });
  8635. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8636. get: function () {
  8637. return this._state === PromiseStates.Rejected;
  8638. },
  8639. enumerable: true,
  8640. configurable: true
  8641. });
  8642. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8643. get: function () {
  8644. return this._state === PromiseStates.Pending;
  8645. },
  8646. enumerable: true,
  8647. configurable: true
  8648. });
  8649. InternalPromise.prototype.value = function () {
  8650. if (!this.isFulfilled) {
  8651. throw new Error("Promise is not fulfilled");
  8652. }
  8653. return this._result;
  8654. };
  8655. InternalPromise.prototype.reason = function () {
  8656. if (!this.isRejected) {
  8657. throw new Error("Promise is not rejected");
  8658. }
  8659. return this._reason;
  8660. };
  8661. InternalPromise.prototype.catch = function (onRejected) {
  8662. return this.then(undefined, onRejected);
  8663. };
  8664. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8665. var newPromise = new InternalPromise();
  8666. newPromise._onFulfilled = onFulfilled;
  8667. newPromise._onRejected = onRejected;
  8668. // Composition
  8669. this._children.push(newPromise);
  8670. if (this._state !== PromiseStates.Pending) {
  8671. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8672. var returnedValue = newPromise._resolve(this._result);
  8673. if (returnedValue !== undefined && returnedValue !== null) {
  8674. if (returnedValue._state !== undefined) {
  8675. var returnedPromise = returnedValue;
  8676. newPromise._children.push(returnedPromise);
  8677. newPromise = returnedPromise;
  8678. }
  8679. else {
  8680. newPromise._result = returnedValue;
  8681. }
  8682. }
  8683. }
  8684. else {
  8685. newPromise._reject(this._reason);
  8686. }
  8687. }
  8688. return newPromise;
  8689. };
  8690. InternalPromise.prototype._moveChildren = function (children) {
  8691. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  8692. if (this.isFulfilled) {
  8693. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  8694. var child = _b[_i];
  8695. child._resolve(this._result);
  8696. }
  8697. }
  8698. else if (this.isRejected) {
  8699. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  8700. var child = _d[_c];
  8701. child._reject(this._reason);
  8702. }
  8703. }
  8704. var _a;
  8705. };
  8706. InternalPromise.prototype._resolve = function (value) {
  8707. try {
  8708. this._state = PromiseStates.Fulfilled;
  8709. this._result = value;
  8710. var returnedValue = null;
  8711. if (this._onFulfilled) {
  8712. returnedValue = this._onFulfilled(value);
  8713. }
  8714. if (returnedValue !== undefined && returnedValue !== null) {
  8715. if (returnedValue._state !== undefined) {
  8716. // Transmit children
  8717. var returnedPromise = returnedValue;
  8718. returnedPromise._moveChildren(this._children);
  8719. }
  8720. else {
  8721. value = returnedValue;
  8722. }
  8723. }
  8724. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8725. var child = _a[_i];
  8726. child._resolve(value);
  8727. }
  8728. return returnedValue;
  8729. }
  8730. catch (e) {
  8731. this._reject(e.message);
  8732. }
  8733. return null;
  8734. };
  8735. InternalPromise.prototype._reject = function (reason) {
  8736. this._state = PromiseStates.Rejected;
  8737. this._reason = reason;
  8738. if (this._onRejected) {
  8739. this._onRejected(reason);
  8740. this._rejectWasConsumed = true;
  8741. }
  8742. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8743. var child = _a[_i];
  8744. if (this._rejectWasConsumed) {
  8745. child._resolve(null);
  8746. }
  8747. else {
  8748. child._reject(reason);
  8749. }
  8750. }
  8751. };
  8752. InternalPromise.resolve = function (value) {
  8753. var newPromise = new InternalPromise();
  8754. newPromise._resolve(value);
  8755. return newPromise;
  8756. };
  8757. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8758. promise.then(function (value) {
  8759. agregator.results[index] = value;
  8760. agregator.count++;
  8761. if (agregator.count === agregator.target) {
  8762. agregator.rootPromise._resolve(agregator.results);
  8763. }
  8764. return null;
  8765. }, function (reason) {
  8766. if (!agregator.rootPromise.isRejected) {
  8767. agregator.rootPromise._reject(reason);
  8768. }
  8769. });
  8770. };
  8771. InternalPromise.all = function (promises) {
  8772. var newPromise = new InternalPromise();
  8773. var agregator = new FulFillmentAgregator();
  8774. agregator.target = promises.length;
  8775. agregator.rootPromise = newPromise;
  8776. if (promises.length) {
  8777. for (var index = 0; index < promises.length; index++) {
  8778. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8779. }
  8780. }
  8781. else {
  8782. newPromise._resolve([]);
  8783. }
  8784. return newPromise;
  8785. };
  8786. return InternalPromise;
  8787. }());
  8788. /**
  8789. * Helper class that provides a small promise polyfill
  8790. */
  8791. var PromisePolyfill = /** @class */ (function () {
  8792. function PromisePolyfill() {
  8793. }
  8794. /**
  8795. * Static function used to check if the polyfill is required
  8796. * If this is the case then the function will inject the polyfill to window.Promise
  8797. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8798. */
  8799. PromisePolyfill.Apply = function (force) {
  8800. if (force === void 0) { force = false; }
  8801. if (force || typeof Promise === 'undefined') {
  8802. var root = window;
  8803. root.Promise = InternalPromise;
  8804. }
  8805. };
  8806. return PromisePolyfill;
  8807. }());
  8808. BABYLON.PromisePolyfill = PromisePolyfill;
  8809. })(BABYLON || (BABYLON = {}));
  8810. //# sourceMappingURL=babylon.promise.js.map
  8811. var BABYLON;
  8812. (function (BABYLON) {
  8813. var _AlphaState = /** @class */ (function () {
  8814. /**
  8815. * Initializes the state.
  8816. */
  8817. function _AlphaState() {
  8818. this._isAlphaBlendDirty = false;
  8819. this._isBlendFunctionParametersDirty = false;
  8820. this._isBlendEquationParametersDirty = false;
  8821. this._isBlendConstantsDirty = false;
  8822. this._alphaBlend = false;
  8823. this._blendFunctionParameters = new Array(4);
  8824. this._blendEquationParameters = new Array(2);
  8825. this._blendConstants = new Array(4);
  8826. this.reset();
  8827. }
  8828. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8829. get: function () {
  8830. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8831. },
  8832. enumerable: true,
  8833. configurable: true
  8834. });
  8835. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8836. get: function () {
  8837. return this._alphaBlend;
  8838. },
  8839. set: function (value) {
  8840. if (this._alphaBlend === value) {
  8841. return;
  8842. }
  8843. this._alphaBlend = value;
  8844. this._isAlphaBlendDirty = true;
  8845. },
  8846. enumerable: true,
  8847. configurable: true
  8848. });
  8849. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8850. if (this._blendConstants[0] === r &&
  8851. this._blendConstants[1] === g &&
  8852. this._blendConstants[2] === b &&
  8853. this._blendConstants[3] === a) {
  8854. return;
  8855. }
  8856. this._blendConstants[0] = r;
  8857. this._blendConstants[1] = g;
  8858. this._blendConstants[2] = b;
  8859. this._blendConstants[3] = a;
  8860. this._isBlendConstantsDirty = true;
  8861. };
  8862. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8863. if (this._blendFunctionParameters[0] === value0 &&
  8864. this._blendFunctionParameters[1] === value1 &&
  8865. this._blendFunctionParameters[2] === value2 &&
  8866. this._blendFunctionParameters[3] === value3) {
  8867. return;
  8868. }
  8869. this._blendFunctionParameters[0] = value0;
  8870. this._blendFunctionParameters[1] = value1;
  8871. this._blendFunctionParameters[2] = value2;
  8872. this._blendFunctionParameters[3] = value3;
  8873. this._isBlendFunctionParametersDirty = true;
  8874. };
  8875. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8876. if (this._blendEquationParameters[0] === rgb &&
  8877. this._blendEquationParameters[1] === alpha) {
  8878. return;
  8879. }
  8880. this._blendEquationParameters[0] = rgb;
  8881. this._blendEquationParameters[1] = alpha;
  8882. this._isBlendEquationParametersDirty = true;
  8883. };
  8884. _AlphaState.prototype.reset = function () {
  8885. this._alphaBlend = false;
  8886. this._blendFunctionParameters[0] = null;
  8887. this._blendFunctionParameters[1] = null;
  8888. this._blendFunctionParameters[2] = null;
  8889. this._blendFunctionParameters[3] = null;
  8890. this._blendEquationParameters[0] = null;
  8891. this._blendEquationParameters[1] = null;
  8892. this._blendConstants[0] = null;
  8893. this._blendConstants[1] = null;
  8894. this._blendConstants[2] = null;
  8895. this._blendConstants[3] = null;
  8896. this._isAlphaBlendDirty = true;
  8897. this._isBlendFunctionParametersDirty = false;
  8898. this._isBlendEquationParametersDirty = false;
  8899. this._isBlendConstantsDirty = false;
  8900. };
  8901. _AlphaState.prototype.apply = function (gl) {
  8902. if (!this.isDirty) {
  8903. return;
  8904. }
  8905. // Alpha blend
  8906. if (this._isAlphaBlendDirty) {
  8907. if (this._alphaBlend) {
  8908. gl.enable(gl.BLEND);
  8909. }
  8910. else {
  8911. gl.disable(gl.BLEND);
  8912. }
  8913. this._isAlphaBlendDirty = false;
  8914. }
  8915. // Alpha function
  8916. if (this._isBlendFunctionParametersDirty) {
  8917. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8918. this._isBlendFunctionParametersDirty = false;
  8919. }
  8920. // Alpha equation
  8921. if (this._isBlendEquationParametersDirty) {
  8922. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8923. this._isBlendEquationParametersDirty = false;
  8924. }
  8925. // Constants
  8926. if (this._isBlendConstantsDirty) {
  8927. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8928. this._isBlendConstantsDirty = false;
  8929. }
  8930. };
  8931. return _AlphaState;
  8932. }());
  8933. BABYLON._AlphaState = _AlphaState;
  8934. })(BABYLON || (BABYLON = {}));
  8935. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8936. var BABYLON;
  8937. (function (BABYLON) {
  8938. var _DepthCullingState = /** @class */ (function () {
  8939. /**
  8940. * Initializes the state.
  8941. */
  8942. function _DepthCullingState() {
  8943. this._isDepthTestDirty = false;
  8944. this._isDepthMaskDirty = false;
  8945. this._isDepthFuncDirty = false;
  8946. this._isCullFaceDirty = false;
  8947. this._isCullDirty = false;
  8948. this._isZOffsetDirty = false;
  8949. this._isFrontFaceDirty = false;
  8950. this.reset();
  8951. }
  8952. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8953. get: function () {
  8954. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8960. get: function () {
  8961. return this._zOffset;
  8962. },
  8963. set: function (value) {
  8964. if (this._zOffset === value) {
  8965. return;
  8966. }
  8967. this._zOffset = value;
  8968. this._isZOffsetDirty = true;
  8969. },
  8970. enumerable: true,
  8971. configurable: true
  8972. });
  8973. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8974. get: function () {
  8975. return this._cullFace;
  8976. },
  8977. set: function (value) {
  8978. if (this._cullFace === value) {
  8979. return;
  8980. }
  8981. this._cullFace = value;
  8982. this._isCullFaceDirty = true;
  8983. },
  8984. enumerable: true,
  8985. configurable: true
  8986. });
  8987. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8988. get: function () {
  8989. return this._cull;
  8990. },
  8991. set: function (value) {
  8992. if (this._cull === value) {
  8993. return;
  8994. }
  8995. this._cull = value;
  8996. this._isCullDirty = true;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9002. get: function () {
  9003. return this._depthFunc;
  9004. },
  9005. set: function (value) {
  9006. if (this._depthFunc === value) {
  9007. return;
  9008. }
  9009. this._depthFunc = value;
  9010. this._isDepthFuncDirty = true;
  9011. },
  9012. enumerable: true,
  9013. configurable: true
  9014. });
  9015. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9016. get: function () {
  9017. return this._depthMask;
  9018. },
  9019. set: function (value) {
  9020. if (this._depthMask === value) {
  9021. return;
  9022. }
  9023. this._depthMask = value;
  9024. this._isDepthMaskDirty = true;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9030. get: function () {
  9031. return this._depthTest;
  9032. },
  9033. set: function (value) {
  9034. if (this._depthTest === value) {
  9035. return;
  9036. }
  9037. this._depthTest = value;
  9038. this._isDepthTestDirty = true;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9044. get: function () {
  9045. return this._frontFace;
  9046. },
  9047. set: function (value) {
  9048. if (this._frontFace === value) {
  9049. return;
  9050. }
  9051. this._frontFace = value;
  9052. this._isFrontFaceDirty = true;
  9053. },
  9054. enumerable: true,
  9055. configurable: true
  9056. });
  9057. _DepthCullingState.prototype.reset = function () {
  9058. this._depthMask = true;
  9059. this._depthTest = true;
  9060. this._depthFunc = null;
  9061. this._cullFace = null;
  9062. this._cull = null;
  9063. this._zOffset = 0;
  9064. this._frontFace = null;
  9065. this._isDepthTestDirty = true;
  9066. this._isDepthMaskDirty = true;
  9067. this._isDepthFuncDirty = false;
  9068. this._isCullFaceDirty = false;
  9069. this._isCullDirty = false;
  9070. this._isZOffsetDirty = false;
  9071. this._isFrontFaceDirty = false;
  9072. };
  9073. _DepthCullingState.prototype.apply = function (gl) {
  9074. if (!this.isDirty) {
  9075. return;
  9076. }
  9077. // Cull
  9078. if (this._isCullDirty) {
  9079. if (this.cull) {
  9080. gl.enable(gl.CULL_FACE);
  9081. }
  9082. else {
  9083. gl.disable(gl.CULL_FACE);
  9084. }
  9085. this._isCullDirty = false;
  9086. }
  9087. // Cull face
  9088. if (this._isCullFaceDirty) {
  9089. gl.cullFace(this.cullFace);
  9090. this._isCullFaceDirty = false;
  9091. }
  9092. // Depth mask
  9093. if (this._isDepthMaskDirty) {
  9094. gl.depthMask(this.depthMask);
  9095. this._isDepthMaskDirty = false;
  9096. }
  9097. // Depth test
  9098. if (this._isDepthTestDirty) {
  9099. if (this.depthTest) {
  9100. gl.enable(gl.DEPTH_TEST);
  9101. }
  9102. else {
  9103. gl.disable(gl.DEPTH_TEST);
  9104. }
  9105. this._isDepthTestDirty = false;
  9106. }
  9107. // Depth func
  9108. if (this._isDepthFuncDirty) {
  9109. gl.depthFunc(this.depthFunc);
  9110. this._isDepthFuncDirty = false;
  9111. }
  9112. // zOffset
  9113. if (this._isZOffsetDirty) {
  9114. if (this.zOffset) {
  9115. gl.enable(gl.POLYGON_OFFSET_FILL);
  9116. gl.polygonOffset(this.zOffset, 0);
  9117. }
  9118. else {
  9119. gl.disable(gl.POLYGON_OFFSET_FILL);
  9120. }
  9121. this._isZOffsetDirty = false;
  9122. }
  9123. // Front face
  9124. if (this._isFrontFaceDirty) {
  9125. gl.frontFace(this.frontFace);
  9126. this._isFrontFaceDirty = false;
  9127. }
  9128. };
  9129. return _DepthCullingState;
  9130. }());
  9131. BABYLON._DepthCullingState = _DepthCullingState;
  9132. })(BABYLON || (BABYLON = {}));
  9133. //# sourceMappingURL=babylon.depthCullingState.js.map
  9134. var BABYLON;
  9135. (function (BABYLON) {
  9136. var _StencilState = /** @class */ (function () {
  9137. function _StencilState() {
  9138. this._isStencilTestDirty = false;
  9139. this._isStencilMaskDirty = false;
  9140. this._isStencilFuncDirty = false;
  9141. this._isStencilOpDirty = false;
  9142. this.reset();
  9143. }
  9144. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9145. get: function () {
  9146. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9147. },
  9148. enumerable: true,
  9149. configurable: true
  9150. });
  9151. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9152. get: function () {
  9153. return this._stencilFunc;
  9154. },
  9155. set: function (value) {
  9156. if (this._stencilFunc === value) {
  9157. return;
  9158. }
  9159. this._stencilFunc = value;
  9160. this._isStencilFuncDirty = true;
  9161. },
  9162. enumerable: true,
  9163. configurable: true
  9164. });
  9165. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9166. get: function () {
  9167. return this._stencilFuncRef;
  9168. },
  9169. set: function (value) {
  9170. if (this._stencilFuncRef === value) {
  9171. return;
  9172. }
  9173. this._stencilFuncRef = value;
  9174. this._isStencilFuncDirty = true;
  9175. },
  9176. enumerable: true,
  9177. configurable: true
  9178. });
  9179. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9180. get: function () {
  9181. return this._stencilFuncMask;
  9182. },
  9183. set: function (value) {
  9184. if (this._stencilFuncMask === value) {
  9185. return;
  9186. }
  9187. this._stencilFuncMask = value;
  9188. this._isStencilFuncDirty = true;
  9189. },
  9190. enumerable: true,
  9191. configurable: true
  9192. });
  9193. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9194. get: function () {
  9195. return this._stencilOpStencilFail;
  9196. },
  9197. set: function (value) {
  9198. if (this._stencilOpStencilFail === value) {
  9199. return;
  9200. }
  9201. this._stencilOpStencilFail = value;
  9202. this._isStencilOpDirty = true;
  9203. },
  9204. enumerable: true,
  9205. configurable: true
  9206. });
  9207. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9208. get: function () {
  9209. return this._stencilOpDepthFail;
  9210. },
  9211. set: function (value) {
  9212. if (this._stencilOpDepthFail === value) {
  9213. return;
  9214. }
  9215. this._stencilOpDepthFail = value;
  9216. this._isStencilOpDirty = true;
  9217. },
  9218. enumerable: true,
  9219. configurable: true
  9220. });
  9221. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9222. get: function () {
  9223. return this._stencilOpStencilDepthPass;
  9224. },
  9225. set: function (value) {
  9226. if (this._stencilOpStencilDepthPass === value) {
  9227. return;
  9228. }
  9229. this._stencilOpStencilDepthPass = value;
  9230. this._isStencilOpDirty = true;
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9236. get: function () {
  9237. return this._stencilMask;
  9238. },
  9239. set: function (value) {
  9240. if (this._stencilMask === value) {
  9241. return;
  9242. }
  9243. this._stencilMask = value;
  9244. this._isStencilMaskDirty = true;
  9245. },
  9246. enumerable: true,
  9247. configurable: true
  9248. });
  9249. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9250. get: function () {
  9251. return this._stencilTest;
  9252. },
  9253. set: function (value) {
  9254. if (this._stencilTest === value) {
  9255. return;
  9256. }
  9257. this._stencilTest = value;
  9258. this._isStencilTestDirty = true;
  9259. },
  9260. enumerable: true,
  9261. configurable: true
  9262. });
  9263. _StencilState.prototype.reset = function () {
  9264. this._stencilTest = false;
  9265. this._stencilMask = 0xFF;
  9266. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9267. this._stencilFuncRef = 1;
  9268. this._stencilFuncMask = 0xFF;
  9269. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9270. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9271. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9272. this._isStencilTestDirty = true;
  9273. this._isStencilMaskDirty = true;
  9274. this._isStencilFuncDirty = true;
  9275. this._isStencilOpDirty = true;
  9276. };
  9277. _StencilState.prototype.apply = function (gl) {
  9278. if (!this.isDirty) {
  9279. return;
  9280. }
  9281. // Stencil test
  9282. if (this._isStencilTestDirty) {
  9283. if (this.stencilTest) {
  9284. gl.enable(gl.STENCIL_TEST);
  9285. }
  9286. else {
  9287. gl.disable(gl.STENCIL_TEST);
  9288. }
  9289. this._isStencilTestDirty = false;
  9290. }
  9291. // Stencil mask
  9292. if (this._isStencilMaskDirty) {
  9293. gl.stencilMask(this.stencilMask);
  9294. this._isStencilMaskDirty = false;
  9295. }
  9296. // Stencil func
  9297. if (this._isStencilFuncDirty) {
  9298. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9299. this._isStencilFuncDirty = false;
  9300. }
  9301. // Stencil op
  9302. if (this._isStencilOpDirty) {
  9303. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9304. this._isStencilOpDirty = false;
  9305. }
  9306. };
  9307. return _StencilState;
  9308. }());
  9309. BABYLON._StencilState = _StencilState;
  9310. })(BABYLON || (BABYLON = {}));
  9311. //# sourceMappingURL=babylon.stencilState.js.map
  9312. var BABYLON;
  9313. (function (BABYLON) {
  9314. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9315. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9316. };
  9317. var compileRawShader = function (gl, source, type) {
  9318. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9319. gl.shaderSource(shader, source);
  9320. gl.compileShader(shader);
  9321. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9322. var log = gl.getShaderInfoLog(shader);
  9323. if (log) {
  9324. throw new Error(log);
  9325. }
  9326. }
  9327. if (!shader) {
  9328. throw new Error("Something went wrong while compile the shader.");
  9329. }
  9330. return shader;
  9331. };
  9332. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9333. var magFilter = gl.NEAREST;
  9334. var minFilter = gl.NEAREST;
  9335. switch (samplingMode) {
  9336. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9337. magFilter = gl.LINEAR;
  9338. if (generateMipMaps) {
  9339. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9340. }
  9341. else {
  9342. minFilter = gl.LINEAR;
  9343. }
  9344. break;
  9345. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9346. magFilter = gl.LINEAR;
  9347. if (generateMipMaps) {
  9348. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9349. }
  9350. else {
  9351. minFilter = gl.LINEAR;
  9352. }
  9353. break;
  9354. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9355. magFilter = gl.NEAREST;
  9356. if (generateMipMaps) {
  9357. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9358. }
  9359. else {
  9360. minFilter = gl.NEAREST;
  9361. }
  9362. break;
  9363. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9364. magFilter = gl.NEAREST;
  9365. if (generateMipMaps) {
  9366. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9367. }
  9368. else {
  9369. minFilter = gl.NEAREST;
  9370. }
  9371. break;
  9372. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9373. magFilter = gl.NEAREST;
  9374. if (generateMipMaps) {
  9375. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9376. }
  9377. else {
  9378. minFilter = gl.LINEAR;
  9379. }
  9380. break;
  9381. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9382. magFilter = gl.NEAREST;
  9383. if (generateMipMaps) {
  9384. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9385. }
  9386. else {
  9387. minFilter = gl.LINEAR;
  9388. }
  9389. break;
  9390. case BABYLON.Texture.NEAREST_LINEAR:
  9391. magFilter = gl.NEAREST;
  9392. minFilter = gl.LINEAR;
  9393. break;
  9394. case BABYLON.Texture.NEAREST_NEAREST:
  9395. magFilter = gl.NEAREST;
  9396. minFilter = gl.NEAREST;
  9397. break;
  9398. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9399. magFilter = gl.LINEAR;
  9400. if (generateMipMaps) {
  9401. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9402. }
  9403. else {
  9404. minFilter = gl.NEAREST;
  9405. }
  9406. break;
  9407. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9408. magFilter = gl.LINEAR;
  9409. if (generateMipMaps) {
  9410. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9411. }
  9412. else {
  9413. minFilter = gl.NEAREST;
  9414. }
  9415. break;
  9416. case BABYLON.Texture.LINEAR_LINEAR:
  9417. magFilter = gl.LINEAR;
  9418. minFilter = gl.LINEAR;
  9419. break;
  9420. case BABYLON.Texture.LINEAR_NEAREST:
  9421. magFilter = gl.LINEAR;
  9422. minFilter = gl.NEAREST;
  9423. break;
  9424. }
  9425. return {
  9426. min: minFilter,
  9427. mag: magFilter
  9428. };
  9429. };
  9430. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9431. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9432. var img;
  9433. var onload = function () {
  9434. loadedImages[index] = img;
  9435. loadedImages._internalCount++;
  9436. if (scene) {
  9437. scene._removePendingData(img);
  9438. }
  9439. if (loadedImages._internalCount === 6) {
  9440. onfinish(loadedImages);
  9441. }
  9442. };
  9443. var onerror = function (message, exception) {
  9444. if (scene) {
  9445. scene._removePendingData(img);
  9446. }
  9447. if (onErrorCallBack) {
  9448. onErrorCallBack(message, exception);
  9449. }
  9450. };
  9451. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9452. if (scene) {
  9453. scene._addPendingData(img);
  9454. }
  9455. };
  9456. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9457. if (onError === void 0) { onError = null; }
  9458. var loadedImages = [];
  9459. loadedImages._internalCount = 0;
  9460. for (var index = 0; index < 6; index++) {
  9461. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9462. }
  9463. };
  9464. var BufferPointer = /** @class */ (function () {
  9465. function BufferPointer() {
  9466. }
  9467. return BufferPointer;
  9468. }());
  9469. var InstancingAttributeInfo = /** @class */ (function () {
  9470. function InstancingAttributeInfo() {
  9471. }
  9472. return InstancingAttributeInfo;
  9473. }());
  9474. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9475. /**
  9476. * Define options used to create a render target texture
  9477. */
  9478. var RenderTargetCreationOptions = /** @class */ (function () {
  9479. function RenderTargetCreationOptions() {
  9480. }
  9481. return RenderTargetCreationOptions;
  9482. }());
  9483. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9484. /**
  9485. * Regroup several parameters relative to the browser in use
  9486. */
  9487. var EngineCapabilities = /** @class */ (function () {
  9488. function EngineCapabilities() {
  9489. }
  9490. return EngineCapabilities;
  9491. }());
  9492. BABYLON.EngineCapabilities = EngineCapabilities;
  9493. /**
  9494. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9495. */
  9496. var Engine = /** @class */ (function () {
  9497. /**
  9498. * @constructor
  9499. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9500. * @param antialias defines enable antialiasing (default: false)
  9501. * @param options defines further options to be sent to the getContext() function
  9502. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9503. */
  9504. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9505. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9506. var _this = this;
  9507. // Public members
  9508. this.forcePOTTextures = false;
  9509. this.isFullscreen = false;
  9510. this.isPointerLock = false;
  9511. this.cullBackFaces = true;
  9512. this.renderEvenInBackground = true;
  9513. this.preventCacheWipeBetweenFrames = false;
  9514. // To enable/disable IDB support and avoid XHR on .manifest
  9515. this.enableOfflineSupport = false;
  9516. this.scenes = new Array();
  9517. this.postProcesses = new Array();
  9518. // Observables
  9519. /**
  9520. * Observable event triggered each time the rendering canvas is resized
  9521. */
  9522. this.onResizeObservable = new BABYLON.Observable();
  9523. /**
  9524. * Observable event triggered each time the canvas loses focus
  9525. */
  9526. this.onCanvasBlurObservable = new BABYLON.Observable();
  9527. /**
  9528. * Observable event triggered each time the canvas gains focus
  9529. */
  9530. this.onCanvasFocusObservable = new BABYLON.Observable();
  9531. /**
  9532. * Observable event triggered each time the canvas receives pointerout event
  9533. */
  9534. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9535. /**
  9536. * Observable event triggered before each texture is initialized
  9537. */
  9538. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9539. //WebVR
  9540. this._vrDisplay = undefined;
  9541. this._vrSupported = false;
  9542. this._vrExclusivePointerMode = false;
  9543. // Uniform buffers list
  9544. this.disableUniformBuffers = false;
  9545. this._uniformBuffers = new Array();
  9546. // Observables
  9547. /**
  9548. * Observable raised when the engine begins a new frame
  9549. */
  9550. this.onBeginFrameObservable = new BABYLON.Observable();
  9551. /**
  9552. * Observable raised when the engine ends the current frame
  9553. */
  9554. this.onEndFrameObservable = new BABYLON.Observable();
  9555. /**
  9556. * Observable raised when the engine is about to compile a shader
  9557. */
  9558. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9559. /**
  9560. * Observable raised when the engine has jsut compiled a shader
  9561. */
  9562. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9563. this._windowIsBackground = false;
  9564. this._webGLVersion = 1.0;
  9565. this._badOS = false;
  9566. this._badDesktopOS = false;
  9567. /**
  9568. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9569. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9570. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9571. */
  9572. this.disableTextureBindingOptimization = false;
  9573. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9574. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9575. this.onVRRequestPresentStart = new BABYLON.Observable();
  9576. this._colorWrite = true;
  9577. this._drawCalls = new BABYLON.PerfCounter();
  9578. this._textureCollisions = new BABYLON.PerfCounter();
  9579. this._renderingQueueLaunched = false;
  9580. this._activeRenderLoops = new Array();
  9581. // Deterministic lockstepMaxSteps
  9582. this._deterministicLockstep = false;
  9583. this._lockstepMaxSteps = 4;
  9584. // Lost context
  9585. this.onContextLostObservable = new BABYLON.Observable();
  9586. this.onContextRestoredObservable = new BABYLON.Observable();
  9587. this._contextWasLost = false;
  9588. this._doNotHandleContextLost = false;
  9589. // FPS
  9590. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9591. this._fps = 60;
  9592. this._deltaTime = 0;
  9593. /**
  9594. * Turn this value on if you want to pause FPS computation when in background
  9595. */
  9596. this.disablePerformanceMonitorInBackground = false;
  9597. // States
  9598. this._depthCullingState = new BABYLON._DepthCullingState();
  9599. this._stencilState = new BABYLON._StencilState();
  9600. this._alphaState = new BABYLON._AlphaState();
  9601. this._alphaMode = Engine.ALPHA_DISABLE;
  9602. // Cache
  9603. this._internalTexturesCache = new Array();
  9604. this._activeChannel = 0;
  9605. this._currentTextureChannel = -1;
  9606. this._boundTexturesCache = {};
  9607. this._compiledEffects = {};
  9608. this._vertexAttribArraysEnabled = [];
  9609. this._uintIndicesCurrentlySet = false;
  9610. this._currentBoundBuffer = new Array();
  9611. this._currentBufferPointers = new Array();
  9612. this._currentInstanceLocations = new Array();
  9613. this._currentInstanceBuffers = new Array();
  9614. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9615. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9616. this._vaoRecordInProgress = false;
  9617. this._mustWipeVertexAttributes = false;
  9618. this._nextFreeTextureSlots = new Array();
  9619. this._maxSimultaneousTextures = 0;
  9620. this._activeRequests = new Array();
  9621. // Hardware supported Compressed Textures
  9622. this._texturesSupported = new Array();
  9623. this._onVRFullScreenTriggered = function () {
  9624. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9625. //get the old size before we change
  9626. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9627. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9628. //get the width and height, change the render size
  9629. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9630. _this.setHardwareScalingLevel(1);
  9631. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9632. }
  9633. else {
  9634. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9635. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9636. }
  9637. };
  9638. this._boundUniforms = {};
  9639. // Register promises
  9640. BABYLON.PromisePolyfill.Apply();
  9641. var canvas = null;
  9642. Engine.Instances.push(this);
  9643. if (!canvasOrContext) {
  9644. return;
  9645. }
  9646. options = options || {};
  9647. if (canvasOrContext.getContext) {
  9648. canvas = canvasOrContext;
  9649. this._renderingCanvas = canvas;
  9650. if (antialias != null) {
  9651. options.antialias = antialias;
  9652. }
  9653. if (options.deterministicLockstep === undefined) {
  9654. options.deterministicLockstep = false;
  9655. }
  9656. if (options.lockstepMaxSteps === undefined) {
  9657. options.lockstepMaxSteps = 4;
  9658. }
  9659. if (options.preserveDrawingBuffer === undefined) {
  9660. options.preserveDrawingBuffer = false;
  9661. }
  9662. if (options.audioEngine === undefined) {
  9663. options.audioEngine = true;
  9664. }
  9665. if (options.stencil === undefined) {
  9666. options.stencil = true;
  9667. }
  9668. this._deterministicLockstep = options.deterministicLockstep;
  9669. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9670. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9671. // Exceptions
  9672. if (navigator && navigator.userAgent) {
  9673. var ua = navigator.userAgent;
  9674. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9675. var exception = _a[_i];
  9676. var key = exception.key;
  9677. var targets = exception.targets;
  9678. if (ua.indexOf(key) > -1) {
  9679. if (exception.capture && exception.captureConstraint) {
  9680. var capture = exception.capture;
  9681. var constraint = exception.captureConstraint;
  9682. var regex = new RegExp(capture);
  9683. var matches = regex.exec(ua);
  9684. if (matches && matches.length > 0) {
  9685. var capturedValue = parseInt(matches[matches.length - 1]);
  9686. if (capturedValue >= constraint) {
  9687. continue;
  9688. }
  9689. }
  9690. }
  9691. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9692. var target = targets_1[_b];
  9693. switch (target) {
  9694. case "uniformBuffer":
  9695. this.disableUniformBuffers = true;
  9696. break;
  9697. case "textureBindingOptimization":
  9698. this.disableTextureBindingOptimization = true;
  9699. break;
  9700. }
  9701. }
  9702. break;
  9703. }
  9704. }
  9705. }
  9706. // GL
  9707. if (!options.disableWebGL2Support) {
  9708. try {
  9709. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9710. if (this._gl) {
  9711. this._webGLVersion = 2.0;
  9712. }
  9713. }
  9714. catch (e) {
  9715. // Do nothing
  9716. }
  9717. }
  9718. if (!this._gl) {
  9719. if (!canvas) {
  9720. throw new Error("The provided canvas is null or undefined.");
  9721. }
  9722. try {
  9723. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9724. }
  9725. catch (e) {
  9726. throw new Error("WebGL not supported");
  9727. }
  9728. }
  9729. if (!this._gl) {
  9730. throw new Error("WebGL not supported");
  9731. }
  9732. this._onCanvasFocus = function () {
  9733. _this.onCanvasFocusObservable.notifyObservers(_this);
  9734. };
  9735. this._onCanvasBlur = function () {
  9736. _this.onCanvasBlurObservable.notifyObservers(_this);
  9737. };
  9738. canvas.addEventListener("focus", this._onCanvasFocus);
  9739. canvas.addEventListener("blur", this._onCanvasBlur);
  9740. this._onBlur = function () {
  9741. if (_this.disablePerformanceMonitorInBackground) {
  9742. _this._performanceMonitor.disable();
  9743. }
  9744. _this._windowIsBackground = true;
  9745. };
  9746. this._onFocus = function () {
  9747. if (_this.disablePerformanceMonitorInBackground) {
  9748. _this._performanceMonitor.enable();
  9749. }
  9750. _this._windowIsBackground = false;
  9751. };
  9752. this._onCanvasPointerOut = function () {
  9753. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9754. };
  9755. window.addEventListener("blur", this._onBlur);
  9756. window.addEventListener("focus", this._onFocus);
  9757. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9758. // Context lost
  9759. if (!this._doNotHandleContextLost) {
  9760. this._onContextLost = function (evt) {
  9761. evt.preventDefault();
  9762. _this._contextWasLost = true;
  9763. BABYLON.Tools.Warn("WebGL context lost.");
  9764. _this.onContextLostObservable.notifyObservers(_this);
  9765. };
  9766. this._onContextRestored = function (evt) {
  9767. // Adding a timeout to avoid race condition at browser level
  9768. setTimeout(function () {
  9769. // Rebuild gl context
  9770. _this._initGLContext();
  9771. // Rebuild effects
  9772. _this._rebuildEffects();
  9773. // Rebuild textures
  9774. _this._rebuildInternalTextures();
  9775. // Rebuild buffers
  9776. _this._rebuildBuffers();
  9777. // Cache
  9778. _this.wipeCaches(true);
  9779. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9780. _this.onContextRestoredObservable.notifyObservers(_this);
  9781. _this._contextWasLost = false;
  9782. }, 0);
  9783. };
  9784. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9785. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9786. }
  9787. }
  9788. else {
  9789. this._gl = canvasOrContext;
  9790. this._renderingCanvas = this._gl.canvas;
  9791. if (this._gl.renderbufferStorageMultisample) {
  9792. this._webGLVersion = 2.0;
  9793. }
  9794. options.stencil = this._gl.getContextAttributes().stencil;
  9795. }
  9796. // Viewport
  9797. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9798. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9799. this.resize();
  9800. this._isStencilEnable = options.stencil ? true : false;
  9801. this._initGLContext();
  9802. if (canvas) {
  9803. // Fullscreen
  9804. this._onFullscreenChange = function () {
  9805. if (document.fullscreen !== undefined) {
  9806. _this.isFullscreen = document.fullscreen;
  9807. }
  9808. else if (document.mozFullScreen !== undefined) {
  9809. _this.isFullscreen = document.mozFullScreen;
  9810. }
  9811. else if (document.webkitIsFullScreen !== undefined) {
  9812. _this.isFullscreen = document.webkitIsFullScreen;
  9813. }
  9814. else if (document.msIsFullScreen !== undefined) {
  9815. _this.isFullscreen = document.msIsFullScreen;
  9816. }
  9817. // Pointer lock
  9818. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9819. canvas.requestPointerLock = canvas.requestPointerLock ||
  9820. canvas.msRequestPointerLock ||
  9821. canvas.mozRequestPointerLock ||
  9822. canvas.webkitRequestPointerLock;
  9823. if (canvas.requestPointerLock) {
  9824. canvas.requestPointerLock();
  9825. }
  9826. }
  9827. };
  9828. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9829. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9830. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9831. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9832. // Pointer lock
  9833. this._onPointerLockChange = function () {
  9834. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9835. document.webkitPointerLockElement === canvas ||
  9836. document.msPointerLockElement === canvas ||
  9837. document.pointerLockElement === canvas);
  9838. };
  9839. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9840. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9841. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9842. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9843. this._onVRDisplayPointerRestricted = function () {
  9844. if (canvas) {
  9845. canvas.requestPointerLock();
  9846. }
  9847. };
  9848. this._onVRDisplayPointerUnrestricted = function () {
  9849. document.exitPointerLock();
  9850. };
  9851. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9852. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9853. }
  9854. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9855. Engine.audioEngine = new BABYLON.AudioEngine();
  9856. }
  9857. // Prepare buffer pointers
  9858. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9859. this._currentBufferPointers[i] = new BufferPointer();
  9860. }
  9861. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9862. // Load WebVR Devices
  9863. if (options.autoEnableWebVR) {
  9864. this.initWebVR();
  9865. }
  9866. // Detect if we are running on a faulty buggy OS.
  9867. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9868. // Detect if we are running on a faulty buggy desktop OS.
  9869. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9870. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9871. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9872. }
  9873. Object.defineProperty(Engine, "LastCreatedEngine", {
  9874. get: function () {
  9875. if (Engine.Instances.length === 0) {
  9876. return null;
  9877. }
  9878. return Engine.Instances[Engine.Instances.length - 1];
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(Engine, "LastCreatedScene", {
  9884. get: function () {
  9885. var lastCreatedEngine = Engine.LastCreatedEngine;
  9886. if (!lastCreatedEngine) {
  9887. return null;
  9888. }
  9889. if (lastCreatedEngine.scenes.length === 0) {
  9890. return null;
  9891. }
  9892. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. /**
  9898. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9899. */
  9900. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9901. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9902. var engine = Engine.Instances[engineIndex];
  9903. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9904. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9905. }
  9906. }
  9907. };
  9908. Object.defineProperty(Engine, "NEVER", {
  9909. get: function () {
  9910. return Engine._NEVER;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(Engine, "ALWAYS", {
  9916. get: function () {
  9917. return Engine._ALWAYS;
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. Object.defineProperty(Engine, "LESS", {
  9923. get: function () {
  9924. return Engine._LESS;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(Engine, "EQUAL", {
  9930. get: function () {
  9931. return Engine._EQUAL;
  9932. },
  9933. enumerable: true,
  9934. configurable: true
  9935. });
  9936. Object.defineProperty(Engine, "LEQUAL", {
  9937. get: function () {
  9938. return Engine._LEQUAL;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Engine, "GREATER", {
  9944. get: function () {
  9945. return Engine._GREATER;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Engine, "GEQUAL", {
  9951. get: function () {
  9952. return Engine._GEQUAL;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(Engine, "NOTEQUAL", {
  9958. get: function () {
  9959. return Engine._NOTEQUAL;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(Engine, "KEEP", {
  9965. get: function () {
  9966. return Engine._KEEP;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(Engine, "REPLACE", {
  9972. get: function () {
  9973. return Engine._REPLACE;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(Engine, "INCR", {
  9979. get: function () {
  9980. return Engine._INCR;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(Engine, "DECR", {
  9986. get: function () {
  9987. return Engine._DECR;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(Engine, "INVERT", {
  9993. get: function () {
  9994. return Engine._INVERT;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(Engine, "INCR_WRAP", {
  10000. get: function () {
  10001. return Engine._INCR_WRAP;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(Engine, "DECR_WRAP", {
  10007. get: function () {
  10008. return Engine._DECR_WRAP;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10014. get: function () {
  10015. return Engine._ALPHA_DISABLE;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10021. get: function () {
  10022. return Engine._ALPHA_ONEONE;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(Engine, "ALPHA_ADD", {
  10028. get: function () {
  10029. return Engine._ALPHA_ADD;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10035. get: function () {
  10036. return Engine._ALPHA_COMBINE;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10042. get: function () {
  10043. return Engine._ALPHA_SUBTRACT;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10049. get: function () {
  10050. return Engine._ALPHA_MULTIPLY;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10056. get: function () {
  10057. return Engine._ALPHA_MAXIMIZED;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10063. get: function () {
  10064. return Engine._ALPHA_PREMULTIPLIED;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10070. get: function () {
  10071. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10077. get: function () {
  10078. return Engine._ALPHA_INTERPOLATE;
  10079. },
  10080. enumerable: true,
  10081. configurable: true
  10082. });
  10083. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10084. get: function () {
  10085. return Engine._ALPHA_SCREENMODE;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10091. get: function () {
  10092. return Engine._DELAYLOADSTATE_NONE;
  10093. },
  10094. enumerable: true,
  10095. configurable: true
  10096. });
  10097. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10098. get: function () {
  10099. return Engine._DELAYLOADSTATE_LOADED;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10105. get: function () {
  10106. return Engine._DELAYLOADSTATE_LOADING;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10112. get: function () {
  10113. return Engine._DELAYLOADSTATE_NOTLOADED;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10119. get: function () {
  10120. return Engine._TEXTUREFORMAT_ALPHA;
  10121. },
  10122. enumerable: true,
  10123. configurable: true
  10124. });
  10125. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10126. get: function () {
  10127. return Engine._TEXTUREFORMAT_LUMINANCE;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10133. get: function () {
  10134. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10140. get: function () {
  10141. return Engine._TEXTUREFORMAT_RGB;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10147. get: function () {
  10148. return Engine._TEXTUREFORMAT_RGBA;
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10154. get: function () {
  10155. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10161. get: function () {
  10162. return Engine._TEXTURETYPE_FLOAT;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10168. get: function () {
  10169. return Engine._TEXTURETYPE_HALF_FLOAT;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10175. get: function () {
  10176. return Engine._SCALEMODE_FLOOR;
  10177. },
  10178. enumerable: true,
  10179. configurable: true
  10180. });
  10181. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10182. get: function () {
  10183. return Engine._SCALEMODE_NEAREST;
  10184. },
  10185. enumerable: true,
  10186. configurable: true
  10187. });
  10188. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10189. get: function () {
  10190. return Engine._SCALEMODE_CEILING;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. Object.defineProperty(Engine, "Version", {
  10196. get: function () {
  10197. return "3.2.0-alpha6";
  10198. },
  10199. enumerable: true,
  10200. configurable: true
  10201. });
  10202. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10203. get: function () {
  10204. return this._vrExclusivePointerMode;
  10205. },
  10206. enumerable: true,
  10207. configurable: true
  10208. });
  10209. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10210. get: function () {
  10211. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10212. },
  10213. enumerable: true,
  10214. configurable: true
  10215. });
  10216. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10217. get: function () {
  10218. return this._webGLVersion < 2 || this.forcePOTTextures;
  10219. },
  10220. enumerable: true,
  10221. configurable: true
  10222. });
  10223. Object.defineProperty(Engine.prototype, "badOS", {
  10224. get: function () {
  10225. return this._badOS;
  10226. },
  10227. enumerable: true,
  10228. configurable: true
  10229. });
  10230. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10231. get: function () {
  10232. return this._badDesktopOS;
  10233. },
  10234. enumerable: true,
  10235. configurable: true
  10236. });
  10237. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10238. get: function () {
  10239. return this._performanceMonitor;
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10245. get: function () {
  10246. return this._texturesSupported;
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10252. get: function () {
  10253. return this._textureFormatInUse;
  10254. },
  10255. enumerable: true,
  10256. configurable: true
  10257. });
  10258. Object.defineProperty(Engine.prototype, "currentViewport", {
  10259. get: function () {
  10260. return this._cachedViewport;
  10261. },
  10262. enumerable: true,
  10263. configurable: true
  10264. });
  10265. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10266. // Empty texture
  10267. get: function () {
  10268. if (!this._emptyTexture) {
  10269. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10270. }
  10271. return this._emptyTexture;
  10272. },
  10273. enumerable: true,
  10274. configurable: true
  10275. });
  10276. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10277. get: function () {
  10278. if (!this._emptyTexture3D) {
  10279. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10280. }
  10281. return this._emptyTexture3D;
  10282. },
  10283. enumerable: true,
  10284. configurable: true
  10285. });
  10286. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10287. get: function () {
  10288. if (!this._emptyCubeTexture) {
  10289. var faceData = new Uint8Array(4);
  10290. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10291. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10292. }
  10293. return this._emptyCubeTexture;
  10294. },
  10295. enumerable: true,
  10296. configurable: true
  10297. });
  10298. Engine.prototype._rebuildInternalTextures = function () {
  10299. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10300. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10301. var internalTexture = currentState_1[_i];
  10302. internalTexture._rebuild();
  10303. }
  10304. };
  10305. Engine.prototype._rebuildEffects = function () {
  10306. for (var key in this._compiledEffects) {
  10307. var effect = this._compiledEffects[key];
  10308. effect._prepareEffect();
  10309. }
  10310. BABYLON.Effect.ResetCache();
  10311. };
  10312. Engine.prototype._rebuildBuffers = function () {
  10313. // Index / Vertex
  10314. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10315. var scene = _a[_i];
  10316. scene.resetCachedMaterial();
  10317. scene._rebuildGeometries();
  10318. scene._rebuildTextures();
  10319. }
  10320. // Uniforms
  10321. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10322. var uniformBuffer = _c[_b];
  10323. uniformBuffer._rebuild();
  10324. }
  10325. };
  10326. Engine.prototype._initGLContext = function () {
  10327. // Caps
  10328. this._caps = new EngineCapabilities();
  10329. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10330. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10331. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10332. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10333. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10334. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10335. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10336. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10337. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10338. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10339. // Infos
  10340. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10341. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10342. if (rendererInfo != null) {
  10343. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10344. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10345. }
  10346. if (!this._glVendor) {
  10347. this._glVendor = "Unknown vendor";
  10348. }
  10349. if (!this._glRenderer) {
  10350. this._glRenderer = "Unknown renderer";
  10351. }
  10352. // Constants
  10353. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10354. if (this._gl.RGBA16F !== 0x881A) {
  10355. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10356. }
  10357. if (this._gl.RGBA32F !== 0x8814) {
  10358. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10359. }
  10360. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10361. this._gl.DEPTH24_STENCIL8 = 35056;
  10362. }
  10363. // Extensions
  10364. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10365. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10366. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10367. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10368. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10369. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10370. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10371. 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');
  10372. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10373. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10374. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10375. this._caps.highPrecisionShaderSupported = true;
  10376. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10377. if (this._caps.timerQuery) {
  10378. if (this._webGLVersion === 1) {
  10379. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10380. }
  10381. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10382. }
  10383. // Checks if some of the format renders first to allow the use of webgl inspector.
  10384. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10385. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10386. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10387. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10388. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10389. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10390. if (this._webGLVersion > 1) {
  10391. this._gl.HALF_FLOAT_OES = 0x140B;
  10392. }
  10393. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10394. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10395. // Draw buffers
  10396. if (this._webGLVersion > 1) {
  10397. this._caps.drawBuffersExtension = true;
  10398. }
  10399. else {
  10400. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10401. if (drawBuffersExtension !== null) {
  10402. this._caps.drawBuffersExtension = true;
  10403. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10404. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10405. for (var i = 0; i < 16; i++) {
  10406. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10407. }
  10408. }
  10409. else {
  10410. this._caps.drawBuffersExtension = false;
  10411. }
  10412. }
  10413. // Depth Texture
  10414. if (this._webGLVersion > 1) {
  10415. this._caps.depthTextureExtension = true;
  10416. }
  10417. else {
  10418. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10419. if (depthTextureExtension != null) {
  10420. this._caps.depthTextureExtension = true;
  10421. }
  10422. }
  10423. // Vertex array object
  10424. if (this._webGLVersion > 1) {
  10425. this._caps.vertexArrayObject = true;
  10426. }
  10427. else {
  10428. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10429. if (vertexArrayObjectExtension != null) {
  10430. this._caps.vertexArrayObject = true;
  10431. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10432. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10433. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10434. }
  10435. else {
  10436. this._caps.vertexArrayObject = false;
  10437. }
  10438. }
  10439. // Instances count
  10440. if (this._webGLVersion > 1) {
  10441. this._caps.instancedArrays = true;
  10442. }
  10443. else {
  10444. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10445. if (instanceExtension != null) {
  10446. this._caps.instancedArrays = true;
  10447. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10448. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10449. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10450. }
  10451. else {
  10452. this._caps.instancedArrays = false;
  10453. }
  10454. }
  10455. // Intelligently add supported compressed formats in order to check for.
  10456. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10457. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10458. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10459. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10460. if (this._caps.astc)
  10461. this.texturesSupported.push('-astc.ktx');
  10462. if (this._caps.s3tc)
  10463. this.texturesSupported.push('-dxt.ktx');
  10464. if (this._caps.pvrtc)
  10465. this.texturesSupported.push('-pvrtc.ktx');
  10466. if (this._caps.etc2)
  10467. this.texturesSupported.push('-etc2.ktx');
  10468. if (this._caps.etc1)
  10469. this.texturesSupported.push('-etc1.ktx');
  10470. if (this._gl.getShaderPrecisionFormat) {
  10471. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10472. if (highp) {
  10473. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10474. }
  10475. }
  10476. // Depth buffer
  10477. this.setDepthBuffer(true);
  10478. this.setDepthFunctionToLessOrEqual();
  10479. this.setDepthWrite(true);
  10480. // Texture maps
  10481. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10482. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10483. this._nextFreeTextureSlots.push(slot);
  10484. }
  10485. };
  10486. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10487. get: function () {
  10488. return this._webGLVersion;
  10489. },
  10490. enumerable: true,
  10491. configurable: true
  10492. });
  10493. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10494. /**
  10495. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10496. */
  10497. get: function () {
  10498. return this._isStencilEnable;
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. Engine.prototype._prepareWorkingCanvas = function () {
  10504. if (this._workingCanvas) {
  10505. return;
  10506. }
  10507. this._workingCanvas = document.createElement("canvas");
  10508. var context = this._workingCanvas.getContext("2d");
  10509. if (context) {
  10510. this._workingContext = context;
  10511. }
  10512. };
  10513. Engine.prototype.resetTextureCache = function () {
  10514. for (var key in this._boundTexturesCache) {
  10515. var boundTexture = this._boundTexturesCache[key];
  10516. if (boundTexture) {
  10517. this._removeDesignatedSlot(boundTexture);
  10518. }
  10519. this._boundTexturesCache[key] = null;
  10520. }
  10521. if (!this.disableTextureBindingOptimization) {
  10522. this._nextFreeTextureSlots = [];
  10523. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10524. this._nextFreeTextureSlots.push(slot);
  10525. }
  10526. }
  10527. this._currentTextureChannel = -1;
  10528. };
  10529. Engine.prototype.isDeterministicLockStep = function () {
  10530. return this._deterministicLockstep;
  10531. };
  10532. Engine.prototype.getLockstepMaxSteps = function () {
  10533. return this._lockstepMaxSteps;
  10534. };
  10535. Engine.prototype.getGlInfo = function () {
  10536. return {
  10537. vendor: this._glVendor,
  10538. renderer: this._glRenderer,
  10539. version: this._glVersion
  10540. };
  10541. };
  10542. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10543. if (useScreen === void 0) { useScreen = false; }
  10544. var viewport = camera.viewport;
  10545. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10546. };
  10547. Engine.prototype.getRenderWidth = function (useScreen) {
  10548. if (useScreen === void 0) { useScreen = false; }
  10549. if (!useScreen && this._currentRenderTarget) {
  10550. return this._currentRenderTarget.width;
  10551. }
  10552. return this._gl.drawingBufferWidth;
  10553. };
  10554. Engine.prototype.getRenderHeight = function (useScreen) {
  10555. if (useScreen === void 0) { useScreen = false; }
  10556. if (!useScreen && this._currentRenderTarget) {
  10557. return this._currentRenderTarget.height;
  10558. }
  10559. return this._gl.drawingBufferHeight;
  10560. };
  10561. Engine.prototype.getRenderingCanvas = function () {
  10562. return this._renderingCanvas;
  10563. };
  10564. Engine.prototype.getRenderingCanvasClientRect = function () {
  10565. if (!this._renderingCanvas) {
  10566. return null;
  10567. }
  10568. return this._renderingCanvas.getBoundingClientRect();
  10569. };
  10570. Engine.prototype.setHardwareScalingLevel = function (level) {
  10571. this._hardwareScalingLevel = level;
  10572. this.resize();
  10573. };
  10574. Engine.prototype.getHardwareScalingLevel = function () {
  10575. return this._hardwareScalingLevel;
  10576. };
  10577. Engine.prototype.getLoadedTexturesCache = function () {
  10578. return this._internalTexturesCache;
  10579. };
  10580. Engine.prototype.getCaps = function () {
  10581. return this._caps;
  10582. };
  10583. Object.defineProperty(Engine.prototype, "drawCalls", {
  10584. /** The number of draw calls submitted last frame */
  10585. get: function () {
  10586. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10587. return 0;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10593. get: function () {
  10594. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10595. return null;
  10596. },
  10597. enumerable: true,
  10598. configurable: true
  10599. });
  10600. Engine.prototype.getDepthFunction = function () {
  10601. return this._depthCullingState.depthFunc;
  10602. };
  10603. Engine.prototype.setDepthFunction = function (depthFunc) {
  10604. this._depthCullingState.depthFunc = depthFunc;
  10605. };
  10606. Engine.prototype.setDepthFunctionToGreater = function () {
  10607. this._depthCullingState.depthFunc = this._gl.GREATER;
  10608. };
  10609. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10610. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10611. };
  10612. Engine.prototype.setDepthFunctionToLess = function () {
  10613. this._depthCullingState.depthFunc = this._gl.LESS;
  10614. };
  10615. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10616. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10617. };
  10618. Engine.prototype.getStencilBuffer = function () {
  10619. return this._stencilState.stencilTest;
  10620. };
  10621. Engine.prototype.setStencilBuffer = function (enable) {
  10622. this._stencilState.stencilTest = enable;
  10623. };
  10624. Engine.prototype.getStencilMask = function () {
  10625. return this._stencilState.stencilMask;
  10626. };
  10627. Engine.prototype.setStencilMask = function (mask) {
  10628. this._stencilState.stencilMask = mask;
  10629. };
  10630. Engine.prototype.getStencilFunction = function () {
  10631. return this._stencilState.stencilFunc;
  10632. };
  10633. Engine.prototype.getStencilFunctionReference = function () {
  10634. return this._stencilState.stencilFuncRef;
  10635. };
  10636. Engine.prototype.getStencilFunctionMask = function () {
  10637. return this._stencilState.stencilFuncMask;
  10638. };
  10639. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10640. this._stencilState.stencilFunc = stencilFunc;
  10641. };
  10642. Engine.prototype.setStencilFunctionReference = function (reference) {
  10643. this._stencilState.stencilFuncRef = reference;
  10644. };
  10645. Engine.prototype.setStencilFunctionMask = function (mask) {
  10646. this._stencilState.stencilFuncMask = mask;
  10647. };
  10648. Engine.prototype.getStencilOperationFail = function () {
  10649. return this._stencilState.stencilOpStencilFail;
  10650. };
  10651. Engine.prototype.getStencilOperationDepthFail = function () {
  10652. return this._stencilState.stencilOpDepthFail;
  10653. };
  10654. Engine.prototype.getStencilOperationPass = function () {
  10655. return this._stencilState.stencilOpStencilDepthPass;
  10656. };
  10657. Engine.prototype.setStencilOperationFail = function (operation) {
  10658. this._stencilState.stencilOpStencilFail = operation;
  10659. };
  10660. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10661. this._stencilState.stencilOpDepthFail = operation;
  10662. };
  10663. Engine.prototype.setStencilOperationPass = function (operation) {
  10664. this._stencilState.stencilOpStencilDepthPass = operation;
  10665. };
  10666. Engine.prototype.setDitheringState = function (value) {
  10667. if (value) {
  10668. this._gl.enable(this._gl.DITHER);
  10669. }
  10670. else {
  10671. this._gl.disable(this._gl.DITHER);
  10672. }
  10673. };
  10674. Engine.prototype.setRasterizerState = function (value) {
  10675. if (value) {
  10676. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10677. }
  10678. else {
  10679. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10680. }
  10681. };
  10682. /**
  10683. * stop executing a render loop function and remove it from the execution array
  10684. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10685. */
  10686. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10687. if (!renderFunction) {
  10688. this._activeRenderLoops = [];
  10689. return;
  10690. }
  10691. var index = this._activeRenderLoops.indexOf(renderFunction);
  10692. if (index >= 0) {
  10693. this._activeRenderLoops.splice(index, 1);
  10694. }
  10695. };
  10696. Engine.prototype._renderLoop = function () {
  10697. if (!this._contextWasLost) {
  10698. var shouldRender = true;
  10699. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10700. shouldRender = false;
  10701. }
  10702. if (shouldRender) {
  10703. // Start new frame
  10704. this.beginFrame();
  10705. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10706. var renderFunction = this._activeRenderLoops[index];
  10707. renderFunction();
  10708. }
  10709. // Present
  10710. this.endFrame();
  10711. }
  10712. }
  10713. if (this._activeRenderLoops.length > 0) {
  10714. // Register new frame
  10715. var requester = null;
  10716. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10717. requester = this._vrDisplay;
  10718. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10719. }
  10720. else {
  10721. this._renderingQueueLaunched = false;
  10722. }
  10723. };
  10724. /**
  10725. * Register and execute a render loop. The engine can have more than one render function.
  10726. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10727. * @example
  10728. * engine.runRenderLoop(function () {
  10729. * scene.render()
  10730. * })
  10731. */
  10732. Engine.prototype.runRenderLoop = function (renderFunction) {
  10733. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10734. return;
  10735. }
  10736. this._activeRenderLoops.push(renderFunction);
  10737. if (!this._renderingQueueLaunched) {
  10738. this._renderingQueueLaunched = true;
  10739. this._bindedRenderFunction = this._renderLoop.bind(this);
  10740. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10741. }
  10742. };
  10743. /**
  10744. * Toggle full screen mode.
  10745. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10746. * @param {any} options - an options object to be sent to the requestFullscreen function
  10747. */
  10748. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10749. if (this.isFullscreen) {
  10750. BABYLON.Tools.ExitFullscreen();
  10751. }
  10752. else {
  10753. this._pointerLockRequested = requestPointerLock;
  10754. if (this._renderingCanvas) {
  10755. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10756. }
  10757. }
  10758. };
  10759. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10760. if (stencil === void 0) { stencil = false; }
  10761. this.applyStates();
  10762. var mode = 0;
  10763. if (backBuffer && color) {
  10764. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10765. mode |= this._gl.COLOR_BUFFER_BIT;
  10766. }
  10767. if (depth) {
  10768. this._gl.clearDepth(1.0);
  10769. mode |= this._gl.DEPTH_BUFFER_BIT;
  10770. }
  10771. if (stencil) {
  10772. this._gl.clearStencil(0);
  10773. mode |= this._gl.STENCIL_BUFFER_BIT;
  10774. }
  10775. this._gl.clear(mode);
  10776. };
  10777. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10778. var gl = this._gl;
  10779. // Save state
  10780. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10781. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10782. // Change state
  10783. gl.enable(gl.SCISSOR_TEST);
  10784. gl.scissor(x, y, width, height);
  10785. // Clear
  10786. this.clear(clearColor, true, true, true);
  10787. // Restore state
  10788. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10789. if (curScissor === true) {
  10790. gl.enable(gl.SCISSOR_TEST);
  10791. }
  10792. else {
  10793. gl.disable(gl.SCISSOR_TEST);
  10794. }
  10795. };
  10796. /**
  10797. * Set the WebGL's viewport
  10798. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10799. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10800. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10801. */
  10802. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10803. var width = requiredWidth || this.getRenderWidth();
  10804. var height = requiredHeight || this.getRenderHeight();
  10805. var x = viewport.x || 0;
  10806. var y = viewport.y || 0;
  10807. this._cachedViewport = viewport;
  10808. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10809. };
  10810. /**
  10811. * Directly set the WebGL Viewport
  10812. * The x, y, width & height are directly passed to the WebGL call
  10813. * @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.
  10814. */
  10815. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10816. var currentViewport = this._cachedViewport;
  10817. this._cachedViewport = null;
  10818. this._gl.viewport(x, y, width, height);
  10819. return currentViewport;
  10820. };
  10821. Engine.prototype.beginFrame = function () {
  10822. this.onBeginFrameObservable.notifyObservers(this);
  10823. this._measureFps();
  10824. };
  10825. Engine.prototype.endFrame = function () {
  10826. //force a flush in case we are using a bad OS.
  10827. if (this._badOS) {
  10828. this.flushFramebuffer();
  10829. }
  10830. //submit frame to the vr device, if enabled
  10831. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10832. // TODO: We should only submit the frame if we read frameData successfully.
  10833. this._vrDisplay.submitFrame();
  10834. }
  10835. this.onEndFrameObservable.notifyObservers(this);
  10836. };
  10837. /**
  10838. * resize the view according to the canvas' size.
  10839. * @example
  10840. * window.addEventListener("resize", function () {
  10841. * engine.resize();
  10842. * });
  10843. */
  10844. Engine.prototype.resize = function () {
  10845. // We're not resizing the size of the canvas while in VR mode & presenting
  10846. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10847. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10848. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10849. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10850. }
  10851. };
  10852. /**
  10853. * force a specific size of the canvas
  10854. * @param {number} width - the new canvas' width
  10855. * @param {number} height - the new canvas' height
  10856. */
  10857. Engine.prototype.setSize = function (width, height) {
  10858. if (!this._renderingCanvas) {
  10859. return;
  10860. }
  10861. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10862. return;
  10863. }
  10864. this._renderingCanvas.width = width;
  10865. this._renderingCanvas.height = height;
  10866. for (var index = 0; index < this.scenes.length; index++) {
  10867. var scene = this.scenes[index];
  10868. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10869. var cam = scene.cameras[camIndex];
  10870. cam._currentRenderId = 0;
  10871. }
  10872. }
  10873. if (this.onResizeObservable.hasObservers) {
  10874. this.onResizeObservable.notifyObservers(this);
  10875. }
  10876. };
  10877. // WebVR functions
  10878. Engine.prototype.isVRDevicePresent = function () {
  10879. return !!this._vrDisplay;
  10880. };
  10881. Engine.prototype.getVRDevice = function () {
  10882. return this._vrDisplay;
  10883. };
  10884. Engine.prototype.initWebVR = function () {
  10885. var _this = this;
  10886. var notifyObservers = function () {
  10887. var eventArgs = {
  10888. vrDisplay: _this._vrDisplay,
  10889. vrSupported: _this._vrSupported
  10890. };
  10891. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10892. };
  10893. if (!this._onVrDisplayConnect) {
  10894. this._onVrDisplayConnect = function (event) {
  10895. _this._vrDisplay = event.display;
  10896. notifyObservers();
  10897. };
  10898. this._onVrDisplayDisconnect = function () {
  10899. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10900. _this._vrDisplay = undefined;
  10901. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10902. notifyObservers();
  10903. };
  10904. this._onVrDisplayPresentChange = function () {
  10905. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10906. };
  10907. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10908. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10909. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10910. }
  10911. this._getVRDisplays(notifyObservers);
  10912. return this.onVRDisplayChangedObservable;
  10913. };
  10914. Engine.prototype.enableVR = function () {
  10915. var _this = this;
  10916. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10917. var onResolved = function () {
  10918. _this.onVRRequestPresentComplete.notifyObservers(true);
  10919. _this._onVRFullScreenTriggered();
  10920. };
  10921. var onRejected = function () {
  10922. _this.onVRRequestPresentComplete.notifyObservers(false);
  10923. };
  10924. this.onVRRequestPresentStart.notifyObservers(this);
  10925. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10926. }
  10927. };
  10928. Engine.prototype.disableVR = function () {
  10929. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10930. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10931. }
  10932. };
  10933. Engine.prototype._getVRDisplays = function (callback) {
  10934. var _this = this;
  10935. var getWebVRDevices = function (devices) {
  10936. _this._vrSupported = true;
  10937. // note that devices may actually be an empty array. This is fine;
  10938. // we expect this._vrDisplay to be undefined in this case.
  10939. return _this._vrDisplay = devices[0];
  10940. };
  10941. if (navigator.getVRDisplays) {
  10942. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10943. // TODO: System CANNOT support WebVR, despite API presence.
  10944. _this._vrSupported = false;
  10945. callback();
  10946. });
  10947. }
  10948. else {
  10949. // TODO: Browser does not support WebVR
  10950. this._vrDisplay = undefined;
  10951. this._vrSupported = false;
  10952. callback();
  10953. }
  10954. };
  10955. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10956. if (this._currentRenderTarget) {
  10957. this.unBindFramebuffer(this._currentRenderTarget);
  10958. }
  10959. this._currentRenderTarget = texture;
  10960. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10961. var gl = this._gl;
  10962. if (texture.isCube) {
  10963. if (faceIndex === undefined) {
  10964. faceIndex = 0;
  10965. }
  10966. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10967. }
  10968. if (this._cachedViewport && !forceFullscreenViewport) {
  10969. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10970. }
  10971. else {
  10972. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10973. }
  10974. this.wipeCaches();
  10975. };
  10976. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10977. if (this._currentFramebuffer !== framebuffer) {
  10978. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10979. this._currentFramebuffer = framebuffer;
  10980. }
  10981. };
  10982. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10983. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10984. this._currentRenderTarget = null;
  10985. // If MSAA, we need to bitblt back to main texture
  10986. var gl = this._gl;
  10987. if (texture._MSAAFramebuffer) {
  10988. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10989. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10990. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10991. }
  10992. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10993. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10994. gl.generateMipmap(gl.TEXTURE_2D);
  10995. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10996. }
  10997. if (onBeforeUnbind) {
  10998. if (texture._MSAAFramebuffer) {
  10999. // Bind the correct framebuffer
  11000. this.bindUnboundFramebuffer(texture._framebuffer);
  11001. }
  11002. onBeforeUnbind();
  11003. }
  11004. this.bindUnboundFramebuffer(null);
  11005. };
  11006. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11007. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11008. this._currentRenderTarget = null;
  11009. // If MSAA, we need to bitblt back to main texture
  11010. var gl = this._gl;
  11011. if (textures[0]._MSAAFramebuffer) {
  11012. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11013. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11014. var attachments = textures[0]._attachments;
  11015. if (!attachments) {
  11016. attachments = new Array(textures.length);
  11017. textures[0]._attachments = attachments;
  11018. }
  11019. for (var i = 0; i < textures.length; i++) {
  11020. var texture = textures[i];
  11021. for (var j = 0; j < attachments.length; j++) {
  11022. attachments[j] = gl.NONE;
  11023. }
  11024. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11025. gl.readBuffer(attachments[i]);
  11026. gl.drawBuffers(attachments);
  11027. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11028. }
  11029. for (var i = 0; i < attachments.length; i++) {
  11030. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11031. }
  11032. gl.drawBuffers(attachments);
  11033. }
  11034. for (var i = 0; i < textures.length; i++) {
  11035. var texture = textures[i];
  11036. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11037. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11038. gl.generateMipmap(gl.TEXTURE_2D);
  11039. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11040. }
  11041. }
  11042. if (onBeforeUnbind) {
  11043. if (textures[0]._MSAAFramebuffer) {
  11044. // Bind the correct framebuffer
  11045. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11046. }
  11047. onBeforeUnbind();
  11048. }
  11049. this.bindUnboundFramebuffer(null);
  11050. };
  11051. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11052. if (texture.generateMipMaps) {
  11053. var gl = this._gl;
  11054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11055. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11056. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11057. }
  11058. };
  11059. Engine.prototype.flushFramebuffer = function () {
  11060. this._gl.flush();
  11061. };
  11062. Engine.prototype.restoreDefaultFramebuffer = function () {
  11063. if (this._currentRenderTarget) {
  11064. this.unBindFramebuffer(this._currentRenderTarget);
  11065. }
  11066. else {
  11067. this.bindUnboundFramebuffer(null);
  11068. }
  11069. if (this._cachedViewport) {
  11070. this.setViewport(this._cachedViewport);
  11071. }
  11072. this.wipeCaches();
  11073. };
  11074. // UBOs
  11075. Engine.prototype.createUniformBuffer = function (elements) {
  11076. var ubo = this._gl.createBuffer();
  11077. if (!ubo) {
  11078. throw new Error("Unable to create uniform buffer");
  11079. }
  11080. this.bindUniformBuffer(ubo);
  11081. if (elements instanceof Float32Array) {
  11082. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11083. }
  11084. else {
  11085. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11086. }
  11087. this.bindUniformBuffer(null);
  11088. ubo.references = 1;
  11089. return ubo;
  11090. };
  11091. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11092. var ubo = this._gl.createBuffer();
  11093. if (!ubo) {
  11094. throw new Error("Unable to create dynamic uniform buffer");
  11095. }
  11096. this.bindUniformBuffer(ubo);
  11097. if (elements instanceof Float32Array) {
  11098. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11099. }
  11100. else {
  11101. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11102. }
  11103. this.bindUniformBuffer(null);
  11104. ubo.references = 1;
  11105. return ubo;
  11106. };
  11107. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11108. this.bindUniformBuffer(uniformBuffer);
  11109. if (offset === undefined) {
  11110. offset = 0;
  11111. }
  11112. if (count === undefined) {
  11113. if (elements instanceof Float32Array) {
  11114. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11115. }
  11116. else {
  11117. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11118. }
  11119. }
  11120. else {
  11121. if (elements instanceof Float32Array) {
  11122. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11123. }
  11124. else {
  11125. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11126. }
  11127. }
  11128. this.bindUniformBuffer(null);
  11129. };
  11130. // VBOs
  11131. Engine.prototype._resetVertexBufferBinding = function () {
  11132. this.bindArrayBuffer(null);
  11133. this._cachedVertexBuffers = null;
  11134. };
  11135. Engine.prototype.createVertexBuffer = function (vertices) {
  11136. var vbo = this._gl.createBuffer();
  11137. if (!vbo) {
  11138. throw new Error("Unable to create vertex buffer");
  11139. }
  11140. this.bindArrayBuffer(vbo);
  11141. if (vertices instanceof Float32Array) {
  11142. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11143. }
  11144. else {
  11145. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11146. }
  11147. this._resetVertexBufferBinding();
  11148. vbo.references = 1;
  11149. return vbo;
  11150. };
  11151. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11152. var vbo = this._gl.createBuffer();
  11153. if (!vbo) {
  11154. throw new Error("Unable to create dynamic vertex buffer");
  11155. }
  11156. this.bindArrayBuffer(vbo);
  11157. if (vertices instanceof Float32Array) {
  11158. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11159. }
  11160. else {
  11161. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11162. }
  11163. this._resetVertexBufferBinding();
  11164. vbo.references = 1;
  11165. return vbo;
  11166. };
  11167. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11168. if (offset === void 0) { offset = 0; }
  11169. // Force cache update
  11170. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11171. this.bindIndexBuffer(indexBuffer);
  11172. var arrayBuffer;
  11173. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11174. arrayBuffer = indices;
  11175. }
  11176. else {
  11177. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11178. }
  11179. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11180. this._resetIndexBufferBinding();
  11181. };
  11182. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11183. this.bindArrayBuffer(vertexBuffer);
  11184. if (offset === undefined) {
  11185. offset = 0;
  11186. }
  11187. if (count === undefined) {
  11188. if (vertices instanceof Float32Array) {
  11189. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11190. }
  11191. else {
  11192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11193. }
  11194. }
  11195. else {
  11196. if (vertices instanceof Float32Array) {
  11197. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11198. }
  11199. else {
  11200. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11201. }
  11202. }
  11203. this._resetVertexBufferBinding();
  11204. };
  11205. Engine.prototype._resetIndexBufferBinding = function () {
  11206. this.bindIndexBuffer(null);
  11207. this._cachedIndexBuffer = null;
  11208. };
  11209. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11210. var vbo = this._gl.createBuffer();
  11211. if (!vbo) {
  11212. throw new Error("Unable to create index buffer");
  11213. }
  11214. this.bindIndexBuffer(vbo);
  11215. // Check for 32 bits indices
  11216. var arrayBuffer;
  11217. var need32Bits = false;
  11218. if (indices instanceof Uint16Array) {
  11219. arrayBuffer = indices;
  11220. }
  11221. else {
  11222. //check 32 bit support
  11223. if (this._caps.uintIndices) {
  11224. if (indices instanceof Uint32Array) {
  11225. arrayBuffer = indices;
  11226. need32Bits = true;
  11227. }
  11228. else {
  11229. //number[] or Int32Array, check if 32 bit is necessary
  11230. for (var index = 0; index < indices.length; index++) {
  11231. if (indices[index] > 65535) {
  11232. need32Bits = true;
  11233. break;
  11234. }
  11235. }
  11236. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11237. }
  11238. }
  11239. else {
  11240. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11241. arrayBuffer = new Uint16Array(indices);
  11242. }
  11243. }
  11244. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11245. this._resetIndexBufferBinding();
  11246. vbo.references = 1;
  11247. vbo.is32Bits = need32Bits;
  11248. return vbo;
  11249. };
  11250. Engine.prototype.bindArrayBuffer = function (buffer) {
  11251. if (!this._vaoRecordInProgress) {
  11252. this._unbindVertexArrayObject();
  11253. }
  11254. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11255. };
  11256. Engine.prototype.bindUniformBuffer = function (buffer) {
  11257. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11258. };
  11259. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11260. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11261. };
  11262. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11263. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11264. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11265. };
  11266. ;
  11267. Engine.prototype.bindIndexBuffer = function (buffer) {
  11268. if (!this._vaoRecordInProgress) {
  11269. this._unbindVertexArrayObject();
  11270. }
  11271. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11272. };
  11273. Engine.prototype.bindBuffer = function (buffer, target) {
  11274. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11275. this._gl.bindBuffer(target, buffer);
  11276. this._currentBoundBuffer[target] = buffer;
  11277. }
  11278. };
  11279. Engine.prototype.updateArrayBuffer = function (data) {
  11280. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11281. };
  11282. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11283. var pointer = this._currentBufferPointers[indx];
  11284. var changed = false;
  11285. if (!pointer.active) {
  11286. changed = true;
  11287. pointer.active = true;
  11288. pointer.index = indx;
  11289. pointer.size = size;
  11290. pointer.type = type;
  11291. pointer.normalized = normalized;
  11292. pointer.stride = stride;
  11293. pointer.offset = offset;
  11294. pointer.buffer = buffer;
  11295. }
  11296. else {
  11297. if (pointer.buffer !== buffer) {
  11298. pointer.buffer = buffer;
  11299. changed = true;
  11300. }
  11301. if (pointer.size !== size) {
  11302. pointer.size = size;
  11303. changed = true;
  11304. }
  11305. if (pointer.type !== type) {
  11306. pointer.type = type;
  11307. changed = true;
  11308. }
  11309. if (pointer.normalized !== normalized) {
  11310. pointer.normalized = normalized;
  11311. changed = true;
  11312. }
  11313. if (pointer.stride !== stride) {
  11314. pointer.stride = stride;
  11315. changed = true;
  11316. }
  11317. if (pointer.offset !== offset) {
  11318. pointer.offset = offset;
  11319. changed = true;
  11320. }
  11321. }
  11322. if (changed || this._vaoRecordInProgress) {
  11323. this.bindArrayBuffer(buffer);
  11324. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11325. }
  11326. };
  11327. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11328. if (indexBuffer == null) {
  11329. return;
  11330. }
  11331. if (this._cachedIndexBuffer !== indexBuffer) {
  11332. this._cachedIndexBuffer = indexBuffer;
  11333. this.bindIndexBuffer(indexBuffer);
  11334. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11335. }
  11336. };
  11337. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11338. var attributes = effect.getAttributesNames();
  11339. if (!this._vaoRecordInProgress) {
  11340. this._unbindVertexArrayObject();
  11341. }
  11342. this.unbindAllAttributes();
  11343. for (var index = 0; index < attributes.length; index++) {
  11344. var order = effect.getAttributeLocation(index);
  11345. if (order >= 0) {
  11346. var vertexBuffer = vertexBuffers[attributes[index]];
  11347. if (!vertexBuffer) {
  11348. continue;
  11349. }
  11350. this._gl.enableVertexAttribArray(order);
  11351. if (!this._vaoRecordInProgress) {
  11352. this._vertexAttribArraysEnabled[order] = true;
  11353. }
  11354. var buffer = vertexBuffer.getBuffer();
  11355. if (buffer) {
  11356. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11357. if (vertexBuffer.getIsInstanced()) {
  11358. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11359. if (!this._vaoRecordInProgress) {
  11360. this._currentInstanceLocations.push(order);
  11361. this._currentInstanceBuffers.push(buffer);
  11362. }
  11363. }
  11364. }
  11365. }
  11366. }
  11367. };
  11368. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11369. var vao = this._gl.createVertexArray();
  11370. this._vaoRecordInProgress = true;
  11371. this._gl.bindVertexArray(vao);
  11372. this._mustWipeVertexAttributes = true;
  11373. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11374. this.bindIndexBuffer(indexBuffer);
  11375. this._vaoRecordInProgress = false;
  11376. this._gl.bindVertexArray(null);
  11377. return vao;
  11378. };
  11379. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11380. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11381. this._cachedVertexArrayObject = vertexArrayObject;
  11382. this._gl.bindVertexArray(vertexArrayObject);
  11383. this._cachedVertexBuffers = null;
  11384. this._cachedIndexBuffer = null;
  11385. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11386. this._mustWipeVertexAttributes = true;
  11387. }
  11388. };
  11389. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11390. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11391. this._cachedVertexBuffers = vertexBuffer;
  11392. this._cachedEffectForVertexBuffers = effect;
  11393. var attributesCount = effect.getAttributesCount();
  11394. this._unbindVertexArrayObject();
  11395. this.unbindAllAttributes();
  11396. var offset = 0;
  11397. for (var index = 0; index < attributesCount; index++) {
  11398. if (index < vertexDeclaration.length) {
  11399. var order = effect.getAttributeLocation(index);
  11400. if (order >= 0) {
  11401. this._gl.enableVertexAttribArray(order);
  11402. this._vertexAttribArraysEnabled[order] = true;
  11403. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11404. }
  11405. offset += vertexDeclaration[index] * 4;
  11406. }
  11407. }
  11408. }
  11409. this._bindIndexBufferWithCache(indexBuffer);
  11410. };
  11411. Engine.prototype._unbindVertexArrayObject = function () {
  11412. if (!this._cachedVertexArrayObject) {
  11413. return;
  11414. }
  11415. this._cachedVertexArrayObject = null;
  11416. this._gl.bindVertexArray(null);
  11417. };
  11418. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11419. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11420. this._cachedVertexBuffers = vertexBuffers;
  11421. this._cachedEffectForVertexBuffers = effect;
  11422. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11423. }
  11424. this._bindIndexBufferWithCache(indexBuffer);
  11425. };
  11426. Engine.prototype.unbindInstanceAttributes = function () {
  11427. var boundBuffer;
  11428. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11429. var instancesBuffer = this._currentInstanceBuffers[i];
  11430. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11431. boundBuffer = instancesBuffer;
  11432. this.bindArrayBuffer(instancesBuffer);
  11433. }
  11434. var offsetLocation = this._currentInstanceLocations[i];
  11435. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11436. }
  11437. this._currentInstanceBuffers.length = 0;
  11438. this._currentInstanceLocations.length = 0;
  11439. };
  11440. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11441. this._gl.deleteVertexArray(vao);
  11442. };
  11443. Engine.prototype._releaseBuffer = function (buffer) {
  11444. buffer.references--;
  11445. if (buffer.references === 0) {
  11446. this._gl.deleteBuffer(buffer);
  11447. return true;
  11448. }
  11449. return false;
  11450. };
  11451. Engine.prototype.createInstancesBuffer = function (capacity) {
  11452. var buffer = this._gl.createBuffer();
  11453. if (!buffer) {
  11454. throw new Error("Unable to create instance buffer");
  11455. }
  11456. buffer.capacity = capacity;
  11457. this.bindArrayBuffer(buffer);
  11458. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11459. return buffer;
  11460. };
  11461. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11462. this._gl.deleteBuffer(buffer);
  11463. };
  11464. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11465. this.bindArrayBuffer(instancesBuffer);
  11466. if (data) {
  11467. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11468. }
  11469. if (offsetLocations[0].index !== undefined) {
  11470. var stride = 0;
  11471. for (var i = 0; i < offsetLocations.length; i++) {
  11472. var ai = offsetLocations[i];
  11473. stride += ai.attributeSize * 4;
  11474. }
  11475. for (var i = 0; i < offsetLocations.length; i++) {
  11476. var ai = offsetLocations[i];
  11477. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11478. this._gl.enableVertexAttribArray(ai.index);
  11479. this._vertexAttribArraysEnabled[ai.index] = true;
  11480. }
  11481. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11482. this._gl.vertexAttribDivisor(ai.index, 1);
  11483. this._currentInstanceLocations.push(ai.index);
  11484. this._currentInstanceBuffers.push(instancesBuffer);
  11485. }
  11486. }
  11487. else {
  11488. for (var index = 0; index < 4; index++) {
  11489. var offsetLocation = offsetLocations[index];
  11490. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11491. this._gl.enableVertexAttribArray(offsetLocation);
  11492. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11493. }
  11494. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11495. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11496. this._currentInstanceLocations.push(offsetLocation);
  11497. this._currentInstanceBuffers.push(instancesBuffer);
  11498. }
  11499. }
  11500. };
  11501. Engine.prototype.applyStates = function () {
  11502. this._depthCullingState.apply(this._gl);
  11503. this._stencilState.apply(this._gl);
  11504. this._alphaState.apply(this._gl);
  11505. };
  11506. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11507. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11508. };
  11509. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11510. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11511. };
  11512. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11513. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11514. };
  11515. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11516. // Apply states
  11517. this.applyStates();
  11518. this._drawCalls.addCount(1, false);
  11519. // Render
  11520. var drawMode = this.DrawMode(fillMode);
  11521. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11522. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11523. if (instancesCount) {
  11524. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11525. }
  11526. else {
  11527. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11528. }
  11529. };
  11530. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11531. // Apply states
  11532. this.applyStates();
  11533. this._drawCalls.addCount(1, false);
  11534. var drawMode = this.DrawMode(fillMode);
  11535. if (instancesCount) {
  11536. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11537. }
  11538. else {
  11539. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11540. }
  11541. };
  11542. Engine.prototype.DrawMode = function (fillMode) {
  11543. switch (fillMode) {
  11544. // Triangle views
  11545. case BABYLON.Material.TriangleFillMode:
  11546. return this._gl.TRIANGLES;
  11547. case BABYLON.Material.PointFillMode:
  11548. return this._gl.POINTS;
  11549. case BABYLON.Material.WireFrameFillMode:
  11550. return this._gl.LINES;
  11551. // Draw modes
  11552. case BABYLON.Material.PointListDrawMode:
  11553. return this._gl.POINTS;
  11554. case BABYLON.Material.LineListDrawMode:
  11555. return this._gl.LINES;
  11556. case BABYLON.Material.LineLoopDrawMode:
  11557. return this._gl.LINE_LOOP;
  11558. case BABYLON.Material.LineStripDrawMode:
  11559. return this._gl.LINE_STRIP;
  11560. case BABYLON.Material.TriangleStripDrawMode:
  11561. return this._gl.TRIANGLE_STRIP;
  11562. case BABYLON.Material.TriangleFanDrawMode:
  11563. return this._gl.TRIANGLE_FAN;
  11564. default:
  11565. return this._gl.TRIANGLES;
  11566. }
  11567. };
  11568. // Shaders
  11569. Engine.prototype._releaseEffect = function (effect) {
  11570. if (this._compiledEffects[effect._key]) {
  11571. delete this._compiledEffects[effect._key];
  11572. this._deleteProgram(effect.getProgram());
  11573. }
  11574. };
  11575. Engine.prototype._deleteProgram = function (program) {
  11576. if (program) {
  11577. program.__SPECTOR_rebuildProgram = null;
  11578. if (program.transformFeedback) {
  11579. this.deleteTransformFeedback(program.transformFeedback);
  11580. program.transformFeedback = null;
  11581. }
  11582. this._gl.deleteProgram(program);
  11583. }
  11584. };
  11585. /**
  11586. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11587. * @param samplers An array of string used to represent textures
  11588. */
  11589. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11590. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11591. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11592. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11593. if (this._compiledEffects[name]) {
  11594. var compiledEffect = this._compiledEffects[name];
  11595. if (onCompiled && compiledEffect.isReady()) {
  11596. onCompiled(compiledEffect);
  11597. }
  11598. return compiledEffect;
  11599. }
  11600. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11601. effect._key = name;
  11602. this._compiledEffects[name] = effect;
  11603. return effect;
  11604. };
  11605. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11606. if (uniformsNames === void 0) { uniformsNames = []; }
  11607. if (samplers === void 0) { samplers = []; }
  11608. if (defines === void 0) { defines = ""; }
  11609. return this.createEffect({
  11610. vertex: "particles",
  11611. fragmentElement: fragmentName
  11612. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11613. };
  11614. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11615. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11616. context = context || this._gl;
  11617. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11618. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11619. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11620. };
  11621. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11622. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11623. context = context || this._gl;
  11624. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11625. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11626. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11627. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11628. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11629. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11630. return program;
  11631. };
  11632. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11633. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11634. var shaderProgram = context.createProgram();
  11635. if (!shaderProgram) {
  11636. throw new Error("Unable to create program");
  11637. }
  11638. context.attachShader(shaderProgram, vertexShader);
  11639. context.attachShader(shaderProgram, fragmentShader);
  11640. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11641. var transformFeedback = this.createTransformFeedback();
  11642. this.bindTransformFeedback(transformFeedback);
  11643. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11644. shaderProgram.transformFeedback = transformFeedback;
  11645. }
  11646. context.linkProgram(shaderProgram);
  11647. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11648. this.bindTransformFeedback(null);
  11649. }
  11650. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11651. if (!linked) {
  11652. context.validateProgram(shaderProgram);
  11653. var error = context.getProgramInfoLog(shaderProgram);
  11654. if (error) {
  11655. throw new Error(error);
  11656. }
  11657. }
  11658. context.deleteShader(vertexShader);
  11659. context.deleteShader(fragmentShader);
  11660. return shaderProgram;
  11661. };
  11662. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11663. var results = new Array();
  11664. for (var index = 0; index < uniformsNames.length; index++) {
  11665. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11666. }
  11667. return results;
  11668. };
  11669. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11670. var results = [];
  11671. for (var index = 0; index < attributesNames.length; index++) {
  11672. try {
  11673. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11674. }
  11675. catch (e) {
  11676. results.push(-1);
  11677. }
  11678. }
  11679. return results;
  11680. };
  11681. Engine.prototype.enableEffect = function (effect) {
  11682. if (!effect) {
  11683. return;
  11684. }
  11685. // Use program
  11686. this.bindSamplers(effect);
  11687. this._currentEffect = effect;
  11688. if (effect.onBind) {
  11689. effect.onBind(effect);
  11690. }
  11691. effect.onBindObservable.notifyObservers(effect);
  11692. };
  11693. Engine.prototype.setIntArray = function (uniform, array) {
  11694. if (!uniform)
  11695. return;
  11696. this._gl.uniform1iv(uniform, array);
  11697. };
  11698. Engine.prototype.setIntArray2 = function (uniform, array) {
  11699. if (!uniform || array.length % 2 !== 0)
  11700. return;
  11701. this._gl.uniform2iv(uniform, array);
  11702. };
  11703. Engine.prototype.setIntArray3 = function (uniform, array) {
  11704. if (!uniform || array.length % 3 !== 0)
  11705. return;
  11706. this._gl.uniform3iv(uniform, array);
  11707. };
  11708. Engine.prototype.setIntArray4 = function (uniform, array) {
  11709. if (!uniform || array.length % 4 !== 0)
  11710. return;
  11711. this._gl.uniform4iv(uniform, array);
  11712. };
  11713. Engine.prototype.setFloatArray = function (uniform, array) {
  11714. if (!uniform)
  11715. return;
  11716. this._gl.uniform1fv(uniform, array);
  11717. };
  11718. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11719. if (!uniform || array.length % 2 !== 0)
  11720. return;
  11721. this._gl.uniform2fv(uniform, array);
  11722. };
  11723. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11724. if (!uniform || array.length % 3 !== 0)
  11725. return;
  11726. this._gl.uniform3fv(uniform, array);
  11727. };
  11728. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11729. if (!uniform || array.length % 4 !== 0)
  11730. return;
  11731. this._gl.uniform4fv(uniform, array);
  11732. };
  11733. Engine.prototype.setArray = function (uniform, array) {
  11734. if (!uniform)
  11735. return;
  11736. this._gl.uniform1fv(uniform, array);
  11737. };
  11738. Engine.prototype.setArray2 = function (uniform, array) {
  11739. if (!uniform || array.length % 2 !== 0)
  11740. return;
  11741. this._gl.uniform2fv(uniform, array);
  11742. };
  11743. Engine.prototype.setArray3 = function (uniform, array) {
  11744. if (!uniform || array.length % 3 !== 0)
  11745. return;
  11746. this._gl.uniform3fv(uniform, array);
  11747. };
  11748. Engine.prototype.setArray4 = function (uniform, array) {
  11749. if (!uniform || array.length % 4 !== 0)
  11750. return;
  11751. this._gl.uniform4fv(uniform, array);
  11752. };
  11753. Engine.prototype.setMatrices = function (uniform, matrices) {
  11754. if (!uniform)
  11755. return;
  11756. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11757. };
  11758. Engine.prototype.setMatrix = function (uniform, matrix) {
  11759. if (!uniform)
  11760. return;
  11761. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11762. };
  11763. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11764. if (!uniform)
  11765. return;
  11766. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11767. };
  11768. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11769. if (!uniform)
  11770. return;
  11771. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11772. };
  11773. Engine.prototype.setInt = function (uniform, value) {
  11774. if (!uniform)
  11775. return;
  11776. this._gl.uniform1i(uniform, value);
  11777. };
  11778. Engine.prototype.setFloat = function (uniform, value) {
  11779. if (!uniform)
  11780. return;
  11781. this._gl.uniform1f(uniform, value);
  11782. };
  11783. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11784. if (!uniform)
  11785. return;
  11786. this._gl.uniform2f(uniform, x, y);
  11787. };
  11788. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11789. if (!uniform)
  11790. return;
  11791. this._gl.uniform3f(uniform, x, y, z);
  11792. };
  11793. Engine.prototype.setBool = function (uniform, bool) {
  11794. if (!uniform)
  11795. return;
  11796. this._gl.uniform1i(uniform, bool);
  11797. };
  11798. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11799. if (!uniform)
  11800. return;
  11801. this._gl.uniform4f(uniform, x, y, z, w);
  11802. };
  11803. Engine.prototype.setColor3 = function (uniform, color3) {
  11804. if (!uniform)
  11805. return;
  11806. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11807. };
  11808. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11809. if (!uniform)
  11810. return;
  11811. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11812. };
  11813. // States
  11814. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11815. if (zOffset === void 0) { zOffset = 0; }
  11816. if (reverseSide === void 0) { reverseSide = false; }
  11817. // Culling
  11818. if (this._depthCullingState.cull !== culling || force) {
  11819. this._depthCullingState.cull = culling;
  11820. }
  11821. // Cull face
  11822. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11823. if (this._depthCullingState.cullFace !== cullFace || force) {
  11824. this._depthCullingState.cullFace = cullFace;
  11825. }
  11826. // Z offset
  11827. this.setZOffset(zOffset);
  11828. // Front face
  11829. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11830. if (this._depthCullingState.frontFace !== frontFace || force) {
  11831. this._depthCullingState.frontFace = frontFace;
  11832. }
  11833. };
  11834. Engine.prototype.setZOffset = function (value) {
  11835. this._depthCullingState.zOffset = value;
  11836. };
  11837. Engine.prototype.getZOffset = function () {
  11838. return this._depthCullingState.zOffset;
  11839. };
  11840. Engine.prototype.setDepthBuffer = function (enable) {
  11841. this._depthCullingState.depthTest = enable;
  11842. };
  11843. Engine.prototype.getDepthWrite = function () {
  11844. return this._depthCullingState.depthMask;
  11845. };
  11846. Engine.prototype.setDepthWrite = function (enable) {
  11847. this._depthCullingState.depthMask = enable;
  11848. };
  11849. Engine.prototype.setColorWrite = function (enable) {
  11850. this._gl.colorMask(enable, enable, enable, enable);
  11851. this._colorWrite = enable;
  11852. };
  11853. Engine.prototype.getColorWrite = function () {
  11854. return this._colorWrite;
  11855. };
  11856. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11857. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11858. };
  11859. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11860. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11861. if (this._alphaMode === mode) {
  11862. return;
  11863. }
  11864. switch (mode) {
  11865. case Engine.ALPHA_DISABLE:
  11866. this._alphaState.alphaBlend = false;
  11867. break;
  11868. case Engine.ALPHA_PREMULTIPLIED:
  11869. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11870. this._alphaState.alphaBlend = true;
  11871. break;
  11872. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11873. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11874. this._alphaState.alphaBlend = true;
  11875. break;
  11876. case Engine.ALPHA_COMBINE:
  11877. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11878. this._alphaState.alphaBlend = true;
  11879. break;
  11880. case Engine.ALPHA_ONEONE:
  11881. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11882. this._alphaState.alphaBlend = true;
  11883. break;
  11884. case Engine.ALPHA_ADD:
  11885. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11886. this._alphaState.alphaBlend = true;
  11887. break;
  11888. case Engine.ALPHA_SUBTRACT:
  11889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11890. this._alphaState.alphaBlend = true;
  11891. break;
  11892. case Engine.ALPHA_MULTIPLY:
  11893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11894. this._alphaState.alphaBlend = true;
  11895. break;
  11896. case Engine.ALPHA_MAXIMIZED:
  11897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11898. this._alphaState.alphaBlend = true;
  11899. break;
  11900. case Engine.ALPHA_INTERPOLATE:
  11901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11902. this._alphaState.alphaBlend = true;
  11903. break;
  11904. case Engine.ALPHA_SCREENMODE:
  11905. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11906. this._alphaState.alphaBlend = true;
  11907. break;
  11908. }
  11909. if (!noDepthWriteChange) {
  11910. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11911. }
  11912. this._alphaMode = mode;
  11913. };
  11914. Engine.prototype.getAlphaMode = function () {
  11915. return this._alphaMode;
  11916. };
  11917. // Textures
  11918. Engine.prototype.wipeCaches = function (bruteForce) {
  11919. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11920. return;
  11921. }
  11922. this._currentEffect = null;
  11923. // 6/8/2017: deltakosh: Should not be required anymore.
  11924. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11925. if (bruteForce) {
  11926. this.resetTextureCache();
  11927. this._currentProgram = null;
  11928. this._stencilState.reset();
  11929. this._depthCullingState.reset();
  11930. this.setDepthFunctionToLessOrEqual();
  11931. this._alphaState.reset();
  11932. }
  11933. this._resetVertexBufferBinding();
  11934. this._cachedIndexBuffer = null;
  11935. this._cachedEffectForVertexBuffers = null;
  11936. this._unbindVertexArrayObject();
  11937. this.bindIndexBuffer(null);
  11938. };
  11939. /**
  11940. * Set the compressed texture format to use, based on the formats you have, and the formats
  11941. * supported by the hardware / browser.
  11942. *
  11943. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11944. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11945. * to API arguments needed to compressed textures. This puts the burden on the container
  11946. * generator to house the arcane code for determining these for current & future formats.
  11947. *
  11948. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11949. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11950. *
  11951. * Note: The result of this call is not taken into account when a texture is base64.
  11952. *
  11953. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11954. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11955. *
  11956. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11957. * @returns The extension selected.
  11958. */
  11959. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11960. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11961. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11962. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11963. return this._textureFormatInUse = this._texturesSupported[i];
  11964. }
  11965. }
  11966. }
  11967. // actively set format to nothing, to allow this to be called more than once
  11968. // and possibly fail the 2nd time
  11969. this._textureFormatInUse = null;
  11970. return null;
  11971. };
  11972. Engine.prototype._createTexture = function () {
  11973. var texture = this._gl.createTexture();
  11974. if (!texture) {
  11975. throw new Error("Unable to create texture");
  11976. }
  11977. return texture;
  11978. };
  11979. /**
  11980. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11981. * @param {string} urlArg- This contains one of the following:
  11982. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11983. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11984. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11985. *
  11986. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11987. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11988. * @param {Scene} scene- Needed for loading to the correct scene.
  11989. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11990. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11991. * @param {callback} onError- Optional callback to be called upon failure.
  11992. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11993. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11994. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11995. *
  11996. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11997. */
  11998. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11999. var _this = this;
  12000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12001. if (onLoad === void 0) { onLoad = null; }
  12002. if (onError === void 0) { onError = null; }
  12003. if (buffer === void 0) { buffer = null; }
  12004. if (fallBack === void 0) { fallBack = null; }
  12005. if (format === void 0) { format = null; }
  12006. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12007. var fromData = url.substr(0, 5) === "data:";
  12008. var fromBlob = url.substr(0, 5) === "blob:";
  12009. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12010. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12011. // establish the file extension, if possible
  12012. var lastDot = url.lastIndexOf('.');
  12013. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12014. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12015. var isTGA = (extension.indexOf(".tga") === 0);
  12016. // determine if a ktx file should be substituted
  12017. var isKTX = false;
  12018. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12019. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12020. isKTX = true;
  12021. }
  12022. if (scene) {
  12023. scene._addPendingData(texture);
  12024. }
  12025. texture.url = url;
  12026. texture.generateMipMaps = !noMipmap;
  12027. texture.samplingMode = samplingMode;
  12028. texture.invertY = invertY;
  12029. if (!this._doNotHandleContextLost) {
  12030. // Keep a link to the buffer only if we plan to handle context lost
  12031. texture._buffer = buffer;
  12032. }
  12033. var onLoadObserver = null;
  12034. if (onLoad && !fallBack) {
  12035. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12036. }
  12037. if (!fallBack)
  12038. this._internalTexturesCache.push(texture);
  12039. var onerror = function (message, exception) {
  12040. if (scene) {
  12041. scene._removePendingData(texture);
  12042. }
  12043. if (onLoadObserver) {
  12044. texture.onLoadedObservable.remove(onLoadObserver);
  12045. }
  12046. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12047. if (isKTX) {
  12048. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12049. }
  12050. else if (BABYLON.Tools.UseFallbackTexture) {
  12051. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12052. }
  12053. if (onError) {
  12054. onError(message || "Unknown error", exception);
  12055. }
  12056. };
  12057. var callback = null;
  12058. // processing for non-image formats
  12059. if (isKTX || isTGA || isDDS) {
  12060. if (isKTX) {
  12061. callback = function (data) {
  12062. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12063. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12064. ktx.uploadLevels(_this._gl, !noMipmap);
  12065. return false;
  12066. }, samplingMode);
  12067. };
  12068. }
  12069. else if (isTGA) {
  12070. callback = function (arrayBuffer) {
  12071. var data = new Uint8Array(arrayBuffer);
  12072. var header = BABYLON.TGATools.GetTGAHeader(data);
  12073. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12074. BABYLON.TGATools.UploadContent(_this._gl, data);
  12075. return false;
  12076. }, samplingMode);
  12077. };
  12078. }
  12079. else if (isDDS) {
  12080. callback = function (data) {
  12081. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12082. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12083. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12084. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12085. return false;
  12086. }, samplingMode);
  12087. };
  12088. }
  12089. if (!buffer) {
  12090. this._loadFile(url, function (data) {
  12091. if (callback) {
  12092. callback(data);
  12093. }
  12094. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12095. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12096. });
  12097. }
  12098. else {
  12099. if (callback) {
  12100. callback(buffer);
  12101. }
  12102. }
  12103. // image format processing
  12104. }
  12105. else {
  12106. var onload = function (img) {
  12107. if (fromBlob && !_this._doNotHandleContextLost) {
  12108. // We need to store the image if we need to rebuild the texture
  12109. // in case of a webgl context lost
  12110. texture._buffer = img;
  12111. }
  12112. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12113. var gl = _this._gl;
  12114. var isPot = (img.width === potWidth && img.height === potHeight);
  12115. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12116. if (isPot) {
  12117. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12118. return false;
  12119. }
  12120. // Using shaders to rescale because canvas.drawImage is lossy
  12121. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12122. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12123. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12128. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12129. _this._releaseTexture(source);
  12130. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12131. continuationCallback();
  12132. });
  12133. return true;
  12134. }, samplingMode);
  12135. };
  12136. if (!fromData || isBase64)
  12137. if (buffer instanceof HTMLImageElement) {
  12138. onload(buffer);
  12139. }
  12140. else {
  12141. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12142. }
  12143. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12144. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12145. else
  12146. onload(buffer);
  12147. }
  12148. return texture;
  12149. };
  12150. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12151. var _this = this;
  12152. var rtt = this.createRenderTargetTexture({
  12153. width: destination.width,
  12154. height: destination.height,
  12155. }, {
  12156. generateMipMaps: false,
  12157. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12158. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12159. generateDepthBuffer: false,
  12160. generateStencilBuffer: false
  12161. });
  12162. if (!this._rescalePostProcess) {
  12163. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12164. }
  12165. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12166. _this._rescalePostProcess.onApply = function (effect) {
  12167. effect._bindTexture("textureSampler", source);
  12168. };
  12169. var hostingScene = scene;
  12170. if (!hostingScene) {
  12171. hostingScene = _this.scenes[_this.scenes.length - 1];
  12172. }
  12173. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12174. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12175. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12176. _this.unBindFramebuffer(rtt);
  12177. _this._releaseTexture(rtt);
  12178. if (onComplete) {
  12179. onComplete();
  12180. }
  12181. });
  12182. };
  12183. Engine.prototype._getInternalFormat = function (format) {
  12184. var internalFormat = this._gl.RGBA;
  12185. switch (format) {
  12186. case Engine.TEXTUREFORMAT_ALPHA:
  12187. internalFormat = this._gl.ALPHA;
  12188. break;
  12189. case Engine.TEXTUREFORMAT_LUMINANCE:
  12190. internalFormat = this._gl.LUMINANCE;
  12191. break;
  12192. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12193. internalFormat = this._gl.LUMINANCE_ALPHA;
  12194. break;
  12195. case Engine.TEXTUREFORMAT_RGB:
  12196. internalFormat = this._gl.RGB;
  12197. break;
  12198. case Engine.TEXTUREFORMAT_RGBA:
  12199. internalFormat = this._gl.RGBA;
  12200. break;
  12201. }
  12202. return internalFormat;
  12203. };
  12204. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12205. if (compression === void 0) { compression = null; }
  12206. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12207. if (!texture) {
  12208. return;
  12209. }
  12210. var internalFormat = this._getInternalFormat(format);
  12211. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12212. var textureType = this._getWebGLTextureType(type);
  12213. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12214. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12215. if (!this._doNotHandleContextLost) {
  12216. texture._bufferView = data;
  12217. texture.format = format;
  12218. texture.type = type;
  12219. texture.invertY = invertY;
  12220. texture._compression = compression;
  12221. }
  12222. if (texture.width % 4 !== 0) {
  12223. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12224. }
  12225. if (compression && data) {
  12226. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12227. }
  12228. else {
  12229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12230. }
  12231. if (texture.generateMipMaps) {
  12232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12233. }
  12234. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12235. // this.resetTextureCache();
  12236. texture.isReady = true;
  12237. };
  12238. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12239. if (compression === void 0) { compression = null; }
  12240. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12242. texture.baseWidth = width;
  12243. texture.baseHeight = height;
  12244. texture.width = width;
  12245. texture.height = height;
  12246. texture.format = format;
  12247. texture.generateMipMaps = generateMipMaps;
  12248. texture.samplingMode = samplingMode;
  12249. texture.invertY = invertY;
  12250. texture._compression = compression;
  12251. texture.type = type;
  12252. if (!this._doNotHandleContextLost) {
  12253. texture._bufferView = data;
  12254. }
  12255. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12256. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12257. // Filters
  12258. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12259. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12260. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12261. if (generateMipMaps) {
  12262. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12263. }
  12264. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12265. this._internalTexturesCache.push(texture);
  12266. return texture;
  12267. };
  12268. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12269. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12270. texture.baseWidth = width;
  12271. texture.baseHeight = height;
  12272. if (generateMipMaps) {
  12273. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12274. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12275. }
  12276. // this.resetTextureCache();
  12277. texture.width = width;
  12278. texture.height = height;
  12279. texture.isReady = false;
  12280. texture.generateMipMaps = generateMipMaps;
  12281. texture.samplingMode = samplingMode;
  12282. this.updateTextureSamplingMode(samplingMode, texture);
  12283. this._internalTexturesCache.push(texture);
  12284. return texture;
  12285. };
  12286. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12287. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12288. if (texture.isCube) {
  12289. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12290. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12291. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12292. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12293. }
  12294. else if (texture.is3D) {
  12295. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12296. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12297. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12298. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12299. }
  12300. else {
  12301. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12302. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12304. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12305. }
  12306. texture.samplingMode = samplingMode;
  12307. };
  12308. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12309. if (premulAlpha === void 0) { premulAlpha = false; }
  12310. if (!texture) {
  12311. return;
  12312. }
  12313. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12314. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12315. if (premulAlpha) {
  12316. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12317. }
  12318. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12319. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12320. if (texture.generateMipMaps) {
  12321. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12322. }
  12323. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12324. if (premulAlpha) {
  12325. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12326. }
  12327. texture.isReady = true;
  12328. };
  12329. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12330. if (!texture || texture._isDisabled) {
  12331. return;
  12332. }
  12333. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12334. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12335. try {
  12336. // Testing video texture support
  12337. if (this._videoTextureSupported === undefined) {
  12338. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12339. if (this._gl.getError() !== 0) {
  12340. this._videoTextureSupported = false;
  12341. }
  12342. else {
  12343. this._videoTextureSupported = true;
  12344. }
  12345. }
  12346. // Copy video through the current working canvas if video texture is not supported
  12347. if (!this._videoTextureSupported) {
  12348. if (!texture._workingCanvas) {
  12349. texture._workingCanvas = document.createElement("canvas");
  12350. var context = texture._workingCanvas.getContext("2d");
  12351. if (!context) {
  12352. throw new Error("Unable to get 2d context");
  12353. }
  12354. texture._workingContext = context;
  12355. texture._workingCanvas.width = texture.width;
  12356. texture._workingCanvas.height = texture.height;
  12357. }
  12358. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12359. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12360. }
  12361. else {
  12362. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12363. }
  12364. if (texture.generateMipMaps) {
  12365. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12366. }
  12367. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12368. // this.resetTextureCache();
  12369. texture.isReady = true;
  12370. }
  12371. catch (ex) {
  12372. // Something unexpected
  12373. // Let's disable the texture
  12374. texture._isDisabled = true;
  12375. }
  12376. };
  12377. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12378. var fullOptions = new RenderTargetCreationOptions();
  12379. if (options !== undefined && typeof options === "object") {
  12380. fullOptions.generateMipMaps = options.generateMipMaps;
  12381. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12382. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12383. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12384. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12385. }
  12386. else {
  12387. fullOptions.generateMipMaps = options;
  12388. fullOptions.generateDepthBuffer = true;
  12389. fullOptions.generateStencilBuffer = false;
  12390. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12391. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12392. }
  12393. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12394. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12395. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12396. }
  12397. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12398. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12399. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12400. }
  12401. var gl = this._gl;
  12402. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12403. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12404. var width = size.width || size;
  12405. var height = size.height || size;
  12406. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12407. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12408. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12409. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12410. }
  12411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12413. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12414. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12415. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12416. // Create the framebuffer
  12417. var framebuffer = gl.createFramebuffer();
  12418. this.bindUnboundFramebuffer(framebuffer);
  12419. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12420. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12421. if (fullOptions.generateMipMaps) {
  12422. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12423. }
  12424. // Unbind
  12425. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12426. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12427. this.bindUnboundFramebuffer(null);
  12428. texture._framebuffer = framebuffer;
  12429. texture.baseWidth = width;
  12430. texture.baseHeight = height;
  12431. texture.width = width;
  12432. texture.height = height;
  12433. texture.isReady = true;
  12434. texture.samples = 1;
  12435. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12436. texture.samplingMode = fullOptions.samplingMode;
  12437. texture.type = fullOptions.type;
  12438. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12439. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12440. // this.resetTextureCache();
  12441. this._internalTexturesCache.push(texture);
  12442. return texture;
  12443. };
  12444. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12445. var generateMipMaps = false;
  12446. var generateDepthBuffer = true;
  12447. var generateStencilBuffer = false;
  12448. var generateDepthTexture = false;
  12449. var textureCount = 1;
  12450. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12451. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12452. var types = [], samplingModes = [];
  12453. if (options !== undefined) {
  12454. generateMipMaps = options.generateMipMaps;
  12455. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12456. generateStencilBuffer = options.generateStencilBuffer;
  12457. generateDepthTexture = options.generateDepthTexture;
  12458. textureCount = options.textureCount || 1;
  12459. if (options.types) {
  12460. types = options.types;
  12461. }
  12462. if (options.samplingModes) {
  12463. samplingModes = options.samplingModes;
  12464. }
  12465. }
  12466. var gl = this._gl;
  12467. // Create the framebuffer
  12468. var framebuffer = gl.createFramebuffer();
  12469. this.bindUnboundFramebuffer(framebuffer);
  12470. var width = size.width || size;
  12471. var height = size.height || size;
  12472. var textures = [];
  12473. var attachments = [];
  12474. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12475. for (var i = 0; i < textureCount; i++) {
  12476. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12477. var type = types[i] || defaultType;
  12478. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12479. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12480. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12481. }
  12482. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12483. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12484. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12485. }
  12486. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12487. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12488. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12489. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12490. }
  12491. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12492. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12493. textures.push(texture);
  12494. attachments.push(attachment);
  12495. gl.activeTexture(gl["TEXTURE" + i]);
  12496. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12497. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12501. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12502. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12503. if (generateMipMaps) {
  12504. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12505. }
  12506. // Unbind
  12507. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12508. texture._framebuffer = framebuffer;
  12509. texture._depthStencilBuffer = depthStencilBuffer;
  12510. texture.baseWidth = width;
  12511. texture.baseHeight = height;
  12512. texture.width = width;
  12513. texture.height = height;
  12514. texture.isReady = true;
  12515. texture.samples = 1;
  12516. texture.generateMipMaps = generateMipMaps;
  12517. texture.samplingMode = samplingMode;
  12518. texture.type = type;
  12519. texture._generateDepthBuffer = generateDepthBuffer;
  12520. texture._generateStencilBuffer = generateStencilBuffer;
  12521. texture._attachments = attachments;
  12522. this._internalTexturesCache.push(texture);
  12523. }
  12524. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12525. // Depth texture
  12526. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12527. gl.activeTexture(gl.TEXTURE0);
  12528. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12533. 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);
  12534. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12535. depthTexture._framebuffer = framebuffer;
  12536. depthTexture.baseWidth = width;
  12537. depthTexture.baseHeight = height;
  12538. depthTexture.width = width;
  12539. depthTexture.height = height;
  12540. depthTexture.isReady = true;
  12541. depthTexture.samples = 1;
  12542. depthTexture.generateMipMaps = generateMipMaps;
  12543. depthTexture.samplingMode = gl.NEAREST;
  12544. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12545. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12546. textures.push(depthTexture);
  12547. this._internalTexturesCache.push(depthTexture);
  12548. }
  12549. gl.drawBuffers(attachments);
  12550. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12551. this.bindUnboundFramebuffer(null);
  12552. this.resetTextureCache();
  12553. return textures;
  12554. };
  12555. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12556. if (samples === void 0) { samples = 1; }
  12557. var depthStencilBuffer = null;
  12558. var gl = this._gl;
  12559. // Create the depth/stencil buffer
  12560. if (generateStencilBuffer) {
  12561. depthStencilBuffer = gl.createRenderbuffer();
  12562. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12563. if (samples > 1) {
  12564. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12565. }
  12566. else {
  12567. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12568. }
  12569. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12570. }
  12571. else if (generateDepthBuffer) {
  12572. depthStencilBuffer = gl.createRenderbuffer();
  12573. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12574. if (samples > 1) {
  12575. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12576. }
  12577. else {
  12578. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12579. }
  12580. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12581. }
  12582. return depthStencilBuffer;
  12583. };
  12584. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12585. if (this.webGLVersion < 2 || !texture) {
  12586. return 1;
  12587. }
  12588. if (texture.samples === samples) {
  12589. return samples;
  12590. }
  12591. var gl = this._gl;
  12592. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12593. // Dispose previous render buffers
  12594. if (texture._depthStencilBuffer) {
  12595. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12596. texture._depthStencilBuffer = null;
  12597. }
  12598. if (texture._MSAAFramebuffer) {
  12599. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12600. texture._MSAAFramebuffer = null;
  12601. }
  12602. if (texture._MSAARenderBuffer) {
  12603. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12604. texture._MSAARenderBuffer = null;
  12605. }
  12606. if (samples > 1) {
  12607. var framebuffer = gl.createFramebuffer();
  12608. if (!framebuffer) {
  12609. throw new Error("Unable to create multi sampled framebuffer");
  12610. }
  12611. texture._MSAAFramebuffer = framebuffer;
  12612. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12613. var colorRenderbuffer = gl.createRenderbuffer();
  12614. if (!colorRenderbuffer) {
  12615. throw new Error("Unable to create multi sampled framebuffer");
  12616. }
  12617. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12618. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12619. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12620. texture._MSAARenderBuffer = colorRenderbuffer;
  12621. }
  12622. else {
  12623. this.bindUnboundFramebuffer(texture._framebuffer);
  12624. }
  12625. texture.samples = samples;
  12626. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12627. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12628. this.bindUnboundFramebuffer(null);
  12629. return samples;
  12630. };
  12631. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12632. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12633. return 1;
  12634. }
  12635. if (textures[0].samples === samples) {
  12636. return samples;
  12637. }
  12638. var gl = this._gl;
  12639. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12640. // Dispose previous render buffers
  12641. if (textures[0]._depthStencilBuffer) {
  12642. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12643. textures[0]._depthStencilBuffer = null;
  12644. }
  12645. if (textures[0]._MSAAFramebuffer) {
  12646. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12647. textures[0]._MSAAFramebuffer = null;
  12648. }
  12649. for (var i = 0; i < textures.length; i++) {
  12650. if (textures[i]._MSAARenderBuffer) {
  12651. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12652. textures[i]._MSAARenderBuffer = null;
  12653. }
  12654. }
  12655. if (samples > 1) {
  12656. var framebuffer = gl.createFramebuffer();
  12657. if (!framebuffer) {
  12658. throw new Error("Unable to create multi sampled framebuffer");
  12659. }
  12660. this.bindUnboundFramebuffer(framebuffer);
  12661. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12662. var attachments = [];
  12663. for (var i = 0; i < textures.length; i++) {
  12664. var texture = textures[i];
  12665. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12666. var colorRenderbuffer = gl.createRenderbuffer();
  12667. if (!colorRenderbuffer) {
  12668. throw new Error("Unable to create multi sampled framebuffer");
  12669. }
  12670. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12671. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12672. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12673. texture._MSAAFramebuffer = framebuffer;
  12674. texture._MSAARenderBuffer = colorRenderbuffer;
  12675. texture.samples = samples;
  12676. texture._depthStencilBuffer = depthStencilBuffer;
  12677. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12678. attachments.push(attachment);
  12679. }
  12680. gl.drawBuffers(attachments);
  12681. }
  12682. else {
  12683. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12684. }
  12685. this.bindUnboundFramebuffer(null);
  12686. return samples;
  12687. };
  12688. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12689. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12690. };
  12691. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12692. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12693. };
  12694. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12695. var gl = this._gl;
  12696. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12697. var generateMipMaps = true;
  12698. var generateDepthBuffer = true;
  12699. var generateStencilBuffer = false;
  12700. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12701. if (options !== undefined) {
  12702. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12703. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12704. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12705. if (options.samplingMode !== undefined) {
  12706. samplingMode = options.samplingMode;
  12707. }
  12708. }
  12709. texture.isCube = true;
  12710. texture.generateMipMaps = generateMipMaps;
  12711. texture.samples = 1;
  12712. texture.samplingMode = samplingMode;
  12713. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12715. for (var face = 0; face < 6; face++) {
  12716. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12717. }
  12718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12722. // Create the framebuffer
  12723. var framebuffer = gl.createFramebuffer();
  12724. this.bindUnboundFramebuffer(framebuffer);
  12725. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12726. // Mipmaps
  12727. if (texture.generateMipMaps) {
  12728. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12729. }
  12730. // Unbind
  12731. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12732. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12733. this.bindUnboundFramebuffer(null);
  12734. texture._framebuffer = framebuffer;
  12735. texture.width = size;
  12736. texture.height = size;
  12737. texture.isReady = true;
  12738. //this.resetTextureCache();
  12739. this._internalTexturesCache.push(texture);
  12740. return texture;
  12741. };
  12742. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12743. var _this = this;
  12744. if (onLoad === void 0) { onLoad = null; }
  12745. if (onError === void 0) { onError = null; }
  12746. if (forcedExtension === void 0) { forcedExtension = null; }
  12747. var callback = function (loadData) {
  12748. if (!loadData) {
  12749. if (onLoad) {
  12750. onLoad(null);
  12751. }
  12752. return;
  12753. }
  12754. var texture = loadData.texture;
  12755. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12756. texture._lodGenerationScale = scale;
  12757. texture._lodGenerationOffset = offset;
  12758. if (_this._caps.textureLOD) {
  12759. // Do not add extra process if texture lod is supported.
  12760. if (onLoad) {
  12761. onLoad(texture);
  12762. }
  12763. return;
  12764. }
  12765. var mipSlices = 3;
  12766. var gl = _this._gl;
  12767. var width = loadData.width;
  12768. if (!width) {
  12769. return;
  12770. }
  12771. var textures = [];
  12772. for (var i = 0; i < mipSlices; i++) {
  12773. //compute LOD from even spacing in smoothness (matching shader calculation)
  12774. var smoothness = i / (mipSlices - 1);
  12775. var roughness = 1 - smoothness;
  12776. var minLODIndex = offset; // roughness = 0
  12777. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12778. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12779. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12780. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12781. glTextureFromLod.isCube = true;
  12782. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12787. if (loadData.isDDS) {
  12788. var info = loadData.info;
  12789. var data = loadData.data;
  12790. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12791. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12792. }
  12793. else {
  12794. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12795. }
  12796. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12797. // Wrap in a base texture for easy binding.
  12798. var lodTexture = new BABYLON.BaseTexture(scene);
  12799. lodTexture.isCube = true;
  12800. lodTexture._texture = glTextureFromLod;
  12801. glTextureFromLod.isReady = true;
  12802. textures.push(lodTexture);
  12803. }
  12804. texture._lodTextureHigh = textures[2];
  12805. texture._lodTextureMid = textures[1];
  12806. texture._lodTextureLow = textures[0];
  12807. if (onLoad) {
  12808. onLoad(texture);
  12809. }
  12810. };
  12811. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12812. };
  12813. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12814. var _this = this;
  12815. if (onLoad === void 0) { onLoad = null; }
  12816. if (onError === void 0) { onError = null; }
  12817. if (forcedExtension === void 0) { forcedExtension = null; }
  12818. var gl = this._gl;
  12819. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12820. texture.isCube = true;
  12821. texture.url = rootUrl;
  12822. texture.generateMipMaps = !noMipmap;
  12823. if (!this._doNotHandleContextLost) {
  12824. texture._extension = forcedExtension;
  12825. texture._files = files;
  12826. }
  12827. var isKTX = false;
  12828. var isDDS = false;
  12829. var lastDot = rootUrl.lastIndexOf('.');
  12830. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12831. if (this._textureFormatInUse) {
  12832. extension = this._textureFormatInUse;
  12833. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12834. isKTX = true;
  12835. }
  12836. else {
  12837. isDDS = (extension === ".dds");
  12838. }
  12839. var onerror = function (request, exception) {
  12840. if (onError && request) {
  12841. onError(request.status + " " + request.statusText, exception);
  12842. }
  12843. };
  12844. if (isKTX) {
  12845. this._loadFile(rootUrl, function (data) {
  12846. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12847. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12848. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12849. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12850. ktx.uploadLevels(_this._gl, !noMipmap);
  12851. _this.setCubeMapTextureParams(gl, loadMipmap);
  12852. texture.width = ktx.pixelWidth;
  12853. texture.height = ktx.pixelHeight;
  12854. texture.isReady = true;
  12855. }, undefined, undefined, true, onerror);
  12856. }
  12857. else if (isDDS) {
  12858. if (files && files.length === 6) {
  12859. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12860. var info;
  12861. var loadMipmap = false;
  12862. var width = 0;
  12863. for (var index = 0; index < imgs.length; index++) {
  12864. var data = imgs[index];
  12865. info = BABYLON.DDSTools.GetDDSInfo(data);
  12866. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12867. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12868. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12869. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12870. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12871. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12872. }
  12873. texture.width = info.width;
  12874. texture.height = info.height;
  12875. texture.type = info.textureType;
  12876. width = info.width;
  12877. }
  12878. _this.setCubeMapTextureParams(gl, loadMipmap);
  12879. texture.isReady = true;
  12880. if (onLoad) {
  12881. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12882. }
  12883. }, files, onError);
  12884. }
  12885. else {
  12886. this._loadFile(rootUrl, function (data) {
  12887. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12888. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12889. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12891. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12892. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12893. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12894. }
  12895. _this.setCubeMapTextureParams(gl, loadMipmap);
  12896. texture.width = info.width;
  12897. texture.height = info.height;
  12898. texture.isReady = true;
  12899. texture.type = info.textureType;
  12900. if (onLoad) {
  12901. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12902. }
  12903. }, undefined, undefined, true, onerror);
  12904. }
  12905. }
  12906. else {
  12907. if (!files) {
  12908. throw new Error("Cannot load cubemap because files were not defined");
  12909. }
  12910. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12911. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12912. var height = width;
  12913. _this._prepareWorkingCanvas();
  12914. if (!_this._workingCanvas || !_this._workingContext) {
  12915. return;
  12916. }
  12917. _this._workingCanvas.width = width;
  12918. _this._workingCanvas.height = height;
  12919. var faces = [
  12920. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12921. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12922. ];
  12923. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12924. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12925. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12926. for (var index = 0; index < faces.length; index++) {
  12927. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12928. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12929. }
  12930. if (!noMipmap) {
  12931. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12932. }
  12933. _this.setCubeMapTextureParams(gl, !noMipmap);
  12934. texture.width = width;
  12935. texture.height = height;
  12936. texture.isReady = true;
  12937. if (format) {
  12938. texture.format = format;
  12939. }
  12940. texture.onLoadedObservable.notifyObservers(texture);
  12941. texture.onLoadedObservable.clear();
  12942. if (onLoad) {
  12943. onLoad();
  12944. }
  12945. }, files, onError);
  12946. }
  12947. this._internalTexturesCache.push(texture);
  12948. return texture;
  12949. };
  12950. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12955. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12956. // this.resetTextureCache();
  12957. };
  12958. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12959. if (compression === void 0) { compression = null; }
  12960. if (level === void 0) { level = 0; }
  12961. texture._bufferViewArray = data;
  12962. texture.format = format;
  12963. texture.type = type;
  12964. texture.invertY = invertY;
  12965. texture._compression = compression;
  12966. var gl = this._gl;
  12967. var textureType = this._getWebGLTextureType(type);
  12968. var internalFormat = this._getInternalFormat(format);
  12969. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12970. var needConversion = false;
  12971. if (internalFormat === gl.RGB) {
  12972. internalFormat = gl.RGBA;
  12973. needConversion = true;
  12974. }
  12975. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12976. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12977. if (texture.width % 4 !== 0) {
  12978. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12979. }
  12980. // Data are known to be in +X +Y +Z -X -Y -Z
  12981. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12982. var faceData = data[faceIndex];
  12983. if (compression) {
  12984. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12985. }
  12986. else {
  12987. if (needConversion) {
  12988. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12989. }
  12990. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12991. }
  12992. }
  12993. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12994. if (isPot && texture.generateMipMaps && level === 0) {
  12995. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12996. }
  12997. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12998. // this.resetTextureCache();
  12999. texture.isReady = true;
  13000. };
  13001. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13002. if (compression === void 0) { compression = null; }
  13003. var gl = this._gl;
  13004. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13005. texture.isCube = true;
  13006. texture.generateMipMaps = generateMipMaps;
  13007. texture.format = format;
  13008. texture.type = type;
  13009. if (!this._doNotHandleContextLost) {
  13010. texture._bufferViewArray = data;
  13011. }
  13012. var textureType = this._getWebGLTextureType(type);
  13013. var internalFormat = this._getInternalFormat(format);
  13014. if (internalFormat === gl.RGB) {
  13015. internalFormat = gl.RGBA;
  13016. }
  13017. var width = size;
  13018. var height = width;
  13019. texture.width = width;
  13020. texture.height = height;
  13021. // Double check on POT to generate Mips.
  13022. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13023. if (!isPot) {
  13024. generateMipMaps = false;
  13025. }
  13026. // Upload data if needed. The texture won't be ready until then.
  13027. if (data) {
  13028. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13029. }
  13030. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13031. // Filters
  13032. if (data && generateMipMaps) {
  13033. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13034. }
  13035. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13038. }
  13039. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13040. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13042. }
  13043. else {
  13044. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13047. }
  13048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13050. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13051. return texture;
  13052. };
  13053. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13054. var _this = this;
  13055. if (onLoad === void 0) { onLoad = null; }
  13056. if (onError === void 0) { onError = null; }
  13057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13058. if (invertY === void 0) { invertY = false; }
  13059. var gl = this._gl;
  13060. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13061. scene._addPendingData(texture);
  13062. texture.url = url;
  13063. this._internalTexturesCache.push(texture);
  13064. var onerror = function (request, exception) {
  13065. scene._removePendingData(texture);
  13066. if (onError && request) {
  13067. onError(request.status + " " + request.statusText, exception);
  13068. }
  13069. };
  13070. var internalCallback = function (data) {
  13071. var width = texture.width;
  13072. var faceDataArrays = callback(data);
  13073. if (!faceDataArrays) {
  13074. return;
  13075. }
  13076. if (mipmmapGenerator) {
  13077. var textureType = _this._getWebGLTextureType(type);
  13078. var internalFormat = _this._getInternalFormat(format);
  13079. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13080. var needConversion = false;
  13081. if (internalFormat === gl.RGB) {
  13082. internalFormat = gl.RGBA;
  13083. needConversion = true;
  13084. }
  13085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13087. var mipData = mipmmapGenerator(faceDataArrays);
  13088. for (var level = 0; level < mipData.length; level++) {
  13089. var mipSize = width >> level;
  13090. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13091. var mipFaceData = mipData[level][faceIndex];
  13092. if (needConversion) {
  13093. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13094. }
  13095. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13096. }
  13097. }
  13098. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13099. }
  13100. else {
  13101. texture.generateMipMaps = !noMipmap;
  13102. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13103. }
  13104. texture.isReady = true;
  13105. // this.resetTextureCache();
  13106. scene._removePendingData(texture);
  13107. if (onLoad) {
  13108. onLoad();
  13109. }
  13110. };
  13111. this._loadFile(url, function (data) {
  13112. internalCallback(data);
  13113. }, undefined, scene.database, true, onerror);
  13114. return texture;
  13115. };
  13116. ;
  13117. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13118. if (compression === void 0) { compression = null; }
  13119. var internalFormat = this._getInternalFormat(format);
  13120. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13121. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13122. if (!this._doNotHandleContextLost) {
  13123. texture._bufferView = data;
  13124. texture.format = format;
  13125. texture.invertY = invertY;
  13126. texture._compression = compression;
  13127. }
  13128. if (texture.width % 4 !== 0) {
  13129. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13130. }
  13131. if (compression && data) {
  13132. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13133. }
  13134. else {
  13135. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13136. }
  13137. if (texture.generateMipMaps) {
  13138. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13139. }
  13140. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13141. // this.resetTextureCache();
  13142. texture.isReady = true;
  13143. };
  13144. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13145. if (compression === void 0) { compression = null; }
  13146. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13147. texture.baseWidth = width;
  13148. texture.baseHeight = height;
  13149. texture.baseDepth = depth;
  13150. texture.width = width;
  13151. texture.height = height;
  13152. texture.depth = depth;
  13153. texture.format = format;
  13154. texture.generateMipMaps = generateMipMaps;
  13155. texture.samplingMode = samplingMode;
  13156. texture.is3D = true;
  13157. if (!this._doNotHandleContextLost) {
  13158. texture._bufferView = data;
  13159. }
  13160. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13161. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13162. // Filters
  13163. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13165. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13166. if (generateMipMaps) {
  13167. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13168. }
  13169. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13170. this._internalTexturesCache.push(texture);
  13171. return texture;
  13172. };
  13173. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13174. var gl = this._gl;
  13175. if (!gl) {
  13176. return;
  13177. }
  13178. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13181. if (!noMipmap && !isCompressed) {
  13182. gl.generateMipmap(gl.TEXTURE_2D);
  13183. }
  13184. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13185. // this.resetTextureCache();
  13186. if (scene) {
  13187. scene._removePendingData(texture);
  13188. }
  13189. texture.onLoadedObservable.notifyObservers(texture);
  13190. texture.onLoadedObservable.clear();
  13191. };
  13192. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13193. var _this = this;
  13194. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13195. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13196. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13197. var gl = this._gl;
  13198. if (!gl) {
  13199. return;
  13200. }
  13201. if (!texture._webGLTexture) {
  13202. // this.resetTextureCache();
  13203. if (scene) {
  13204. scene._removePendingData(texture);
  13205. }
  13206. return;
  13207. }
  13208. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13210. texture.baseWidth = width;
  13211. texture.baseHeight = height;
  13212. texture.width = potWidth;
  13213. texture.height = potHeight;
  13214. texture.isReady = true;
  13215. if (processFunction(potWidth, potHeight, function () {
  13216. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13217. })) {
  13218. // Returning as texture needs extra async steps
  13219. return;
  13220. }
  13221. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13222. };
  13223. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13224. // Create new RGBA data container.
  13225. var rgbaData;
  13226. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13227. rgbaData = new Float32Array(width * height * 4);
  13228. }
  13229. else {
  13230. rgbaData = new Uint32Array(width * height * 4);
  13231. }
  13232. // Convert each pixel.
  13233. for (var x = 0; x < width; x++) {
  13234. for (var y = 0; y < height; y++) {
  13235. var index = (y * width + x) * 3;
  13236. var newIndex = (y * width + x) * 4;
  13237. // Map Old Value to new value.
  13238. rgbaData[newIndex + 0] = rgbData[index + 0];
  13239. rgbaData[newIndex + 1] = rgbData[index + 1];
  13240. rgbaData[newIndex + 2] = rgbData[index + 2];
  13241. // Add fully opaque alpha channel.
  13242. rgbaData[newIndex + 3] = 1;
  13243. }
  13244. }
  13245. return rgbaData;
  13246. };
  13247. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13248. var gl = this._gl;
  13249. if (texture._framebuffer) {
  13250. gl.deleteFramebuffer(texture._framebuffer);
  13251. texture._framebuffer = null;
  13252. }
  13253. if (texture._depthStencilBuffer) {
  13254. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13255. texture._depthStencilBuffer = null;
  13256. }
  13257. if (texture._MSAAFramebuffer) {
  13258. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13259. texture._MSAAFramebuffer = null;
  13260. }
  13261. if (texture._MSAARenderBuffer) {
  13262. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13263. texture._MSAARenderBuffer = null;
  13264. }
  13265. };
  13266. Engine.prototype._releaseTexture = function (texture) {
  13267. var gl = this._gl;
  13268. this._releaseFramebufferObjects(texture);
  13269. gl.deleteTexture(texture._webGLTexture);
  13270. // Unbind channels
  13271. this.unbindAllTextures();
  13272. var index = this._internalTexturesCache.indexOf(texture);
  13273. if (index !== -1) {
  13274. this._internalTexturesCache.splice(index, 1);
  13275. }
  13276. // Integrated fixed lod samplers.
  13277. if (texture._lodTextureHigh) {
  13278. texture._lodTextureHigh.dispose();
  13279. }
  13280. if (texture._lodTextureMid) {
  13281. texture._lodTextureMid.dispose();
  13282. }
  13283. if (texture._lodTextureLow) {
  13284. texture._lodTextureLow.dispose();
  13285. }
  13286. };
  13287. Engine.prototype.setProgram = function (program) {
  13288. if (this._currentProgram !== program) {
  13289. this._gl.useProgram(program);
  13290. this._currentProgram = program;
  13291. }
  13292. };
  13293. Engine.prototype.bindSamplers = function (effect) {
  13294. this.setProgram(effect.getProgram());
  13295. var samplers = effect.getSamplers();
  13296. for (var index = 0; index < samplers.length; index++) {
  13297. var uniform = effect.getUniform(samplers[index]);
  13298. if (uniform) {
  13299. this._boundUniforms[index] = uniform;
  13300. }
  13301. }
  13302. this._currentEffect = null;
  13303. };
  13304. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13305. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13306. return;
  13307. }
  13308. // Remove
  13309. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13310. // Bind last to it
  13311. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13312. // Bind to dummy
  13313. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13314. };
  13315. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13316. if (!internalTexture) {
  13317. return -1;
  13318. }
  13319. internalTexture._initialSlot = channel;
  13320. if (this.disableTextureBindingOptimization) {
  13321. if (channel !== internalTexture._designatedSlot) {
  13322. this._textureCollisions.addCount(1, false);
  13323. }
  13324. }
  13325. else {
  13326. if (channel !== internalTexture._designatedSlot) {
  13327. if (internalTexture._designatedSlot > -1) {
  13328. return internalTexture._designatedSlot;
  13329. }
  13330. else {
  13331. // No slot for this texture, let's pick a new one (if we find a free slot)
  13332. if (this._nextFreeTextureSlots.length) {
  13333. return this._nextFreeTextureSlots[0];
  13334. }
  13335. // We need to recycle the oldest bound texture, sorry.
  13336. this._textureCollisions.addCount(1, false);
  13337. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13338. }
  13339. }
  13340. }
  13341. return channel;
  13342. };
  13343. Engine.prototype._linkTrackers = function (previous, next) {
  13344. previous.next = next;
  13345. next.previous = previous;
  13346. };
  13347. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13348. var currentSlot = internalTexture._designatedSlot;
  13349. if (currentSlot === -1) {
  13350. return -1;
  13351. }
  13352. internalTexture._designatedSlot = -1;
  13353. if (this.disableTextureBindingOptimization) {
  13354. return -1;
  13355. }
  13356. // Remove from bound list
  13357. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13358. // Free the slot
  13359. this._boundTexturesCache[currentSlot] = null;
  13360. this._nextFreeTextureSlots.push(currentSlot);
  13361. return currentSlot;
  13362. };
  13363. Engine.prototype._activateCurrentTexture = function () {
  13364. if (this._currentTextureChannel !== this._activeChannel) {
  13365. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13366. this._currentTextureChannel = this._activeChannel;
  13367. }
  13368. };
  13369. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13370. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13371. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13372. this._activeChannel = texture._designatedSlot;
  13373. }
  13374. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13375. var isTextureForRendering = texture && texture._initialSlot > -1;
  13376. if (currentTextureBound !== texture) {
  13377. if (currentTextureBound) {
  13378. this._removeDesignatedSlot(currentTextureBound);
  13379. }
  13380. this._activateCurrentTexture();
  13381. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13382. this._boundTexturesCache[this._activeChannel] = texture;
  13383. if (texture) {
  13384. if (!this.disableTextureBindingOptimization) {
  13385. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13386. if (slotIndex > -1) {
  13387. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13388. }
  13389. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13390. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13391. }
  13392. texture._designatedSlot = this._activeChannel;
  13393. }
  13394. }
  13395. else if (forTextureDataUpdate) {
  13396. this._activateCurrentTexture();
  13397. }
  13398. if (isTextureForRendering && !forTextureDataUpdate) {
  13399. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13400. }
  13401. };
  13402. Engine.prototype._bindTexture = function (channel, texture) {
  13403. if (channel < 0) {
  13404. return;
  13405. }
  13406. if (texture) {
  13407. channel = this._getCorrectTextureChannel(channel, texture);
  13408. }
  13409. this._activeChannel = channel;
  13410. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13411. };
  13412. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13413. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13414. };
  13415. Engine.prototype.unbindAllTextures = function () {
  13416. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13417. this._activeChannel = channel;
  13418. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13419. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13420. if (this.webGLVersion > 1) {
  13421. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13422. }
  13423. }
  13424. };
  13425. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13426. if (channel < 0) {
  13427. return;
  13428. }
  13429. if (uniform) {
  13430. this._boundUniforms[channel] = uniform;
  13431. }
  13432. this._setTexture(channel, texture);
  13433. };
  13434. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13435. var uniform = this._boundUniforms[sourceSlot];
  13436. if (uniform._currentState === destination) {
  13437. return;
  13438. }
  13439. this._gl.uniform1i(uniform, destination);
  13440. uniform._currentState = destination;
  13441. };
  13442. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13443. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13444. // Not ready?
  13445. if (!texture) {
  13446. if (this._boundTexturesCache[channel] != null) {
  13447. this._activeChannel = channel;
  13448. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13450. if (this.webGLVersion > 1) {
  13451. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13452. }
  13453. }
  13454. return false;
  13455. }
  13456. // Video
  13457. if (texture.video) {
  13458. this._activeChannel = channel;
  13459. texture.update();
  13460. }
  13461. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13462. texture.delayLoad();
  13463. return false;
  13464. }
  13465. var internalTexture;
  13466. if (texture.isReady()) {
  13467. internalTexture = texture.getInternalTexture();
  13468. }
  13469. else if (texture.isCube) {
  13470. internalTexture = this.emptyCubeTexture;
  13471. }
  13472. else if (texture.is3D) {
  13473. internalTexture = this.emptyTexture3D;
  13474. }
  13475. else {
  13476. internalTexture = this.emptyTexture;
  13477. }
  13478. if (!isPartOfTextureArray) {
  13479. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13480. }
  13481. if (this._boundTexturesCache[channel] === internalTexture) {
  13482. this._moveBoundTextureOnTop(internalTexture);
  13483. if (!isPartOfTextureArray) {
  13484. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13485. }
  13486. return false;
  13487. }
  13488. this._activeChannel = channel;
  13489. if (internalTexture && internalTexture.is3D) {
  13490. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13491. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13492. internalTexture._cachedWrapU = texture.wrapU;
  13493. switch (texture.wrapU) {
  13494. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13495. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13496. break;
  13497. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13498. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13499. break;
  13500. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13501. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13502. break;
  13503. }
  13504. }
  13505. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13506. internalTexture._cachedWrapV = texture.wrapV;
  13507. switch (texture.wrapV) {
  13508. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13509. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13510. break;
  13511. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13512. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13513. break;
  13514. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13515. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13516. break;
  13517. }
  13518. }
  13519. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13520. internalTexture._cachedWrapR = texture.wrapR;
  13521. switch (texture.wrapV) {
  13522. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13523. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13524. break;
  13525. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13526. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13527. break;
  13528. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13529. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13530. break;
  13531. }
  13532. }
  13533. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13534. }
  13535. else if (internalTexture && internalTexture.isCube) {
  13536. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13537. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13538. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13539. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13540. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13541. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13542. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13543. }
  13544. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13545. }
  13546. else {
  13547. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13548. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13549. internalTexture._cachedWrapU = texture.wrapU;
  13550. switch (texture.wrapU) {
  13551. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13552. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13553. break;
  13554. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13555. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13556. break;
  13557. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13558. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13559. break;
  13560. }
  13561. }
  13562. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13563. internalTexture._cachedWrapV = texture.wrapV;
  13564. switch (texture.wrapV) {
  13565. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13566. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13567. break;
  13568. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13569. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13570. break;
  13571. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13572. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13573. break;
  13574. }
  13575. }
  13576. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13577. }
  13578. return true;
  13579. };
  13580. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13581. if (channel < 0 || !uniform) {
  13582. return;
  13583. }
  13584. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13585. this._textureUnits = new Int32Array(textures.length);
  13586. }
  13587. for (var i = 0; i < textures.length; i++) {
  13588. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13589. }
  13590. this._gl.uniform1iv(uniform, this._textureUnits);
  13591. for (var index = 0; index < textures.length; index++) {
  13592. this._setTexture(this._textureUnits[index], textures[index], true);
  13593. }
  13594. };
  13595. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13596. var internalTexture = texture.getInternalTexture();
  13597. if (!internalTexture) {
  13598. return;
  13599. }
  13600. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13601. var value = texture.anisotropicFilteringLevel;
  13602. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13603. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13604. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13605. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13606. }
  13607. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13608. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13609. internalTexture._cachedAnisotropicFilteringLevel = value;
  13610. }
  13611. };
  13612. Engine.prototype.readPixels = function (x, y, width, height) {
  13613. var data = new Uint8Array(height * width * 4);
  13614. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13615. return data;
  13616. };
  13617. /**
  13618. * Add an externaly attached data from its key.
  13619. * This method call will fail and return false, if such key already exists.
  13620. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13621. * @param key the unique key that identifies the data
  13622. * @param data the data object to associate to the key for this Engine instance
  13623. * @return true if no such key were already present and the data was added successfully, false otherwise
  13624. */
  13625. Engine.prototype.addExternalData = function (key, data) {
  13626. if (!this._externalData) {
  13627. this._externalData = new BABYLON.StringDictionary();
  13628. }
  13629. return this._externalData.add(key, data);
  13630. };
  13631. /**
  13632. * Get an externaly attached data from its key
  13633. * @param key the unique key that identifies the data
  13634. * @return the associated data, if present (can be null), or undefined if not present
  13635. */
  13636. Engine.prototype.getExternalData = function (key) {
  13637. if (!this._externalData) {
  13638. this._externalData = new BABYLON.StringDictionary();
  13639. }
  13640. return this._externalData.get(key);
  13641. };
  13642. /**
  13643. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13644. * @param key the unique key that identifies the data
  13645. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13646. * @return the associated data, can be null if the factory returned null.
  13647. */
  13648. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13649. if (!this._externalData) {
  13650. this._externalData = new BABYLON.StringDictionary();
  13651. }
  13652. return this._externalData.getOrAddWithFactory(key, factory);
  13653. };
  13654. /**
  13655. * Remove an externaly attached data from the Engine instance
  13656. * @param key the unique key that identifies the data
  13657. * @return true if the data was successfully removed, false if it doesn't exist
  13658. */
  13659. Engine.prototype.removeExternalData = function (key) {
  13660. if (!this._externalData) {
  13661. this._externalData = new BABYLON.StringDictionary();
  13662. }
  13663. return this._externalData.remove(key);
  13664. };
  13665. Engine.prototype.unbindAllAttributes = function () {
  13666. if (this._mustWipeVertexAttributes) {
  13667. this._mustWipeVertexAttributes = false;
  13668. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13669. this._gl.disableVertexAttribArray(i);
  13670. this._vertexAttribArraysEnabled[i] = false;
  13671. this._currentBufferPointers[i].active = false;
  13672. }
  13673. return;
  13674. }
  13675. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13676. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13677. continue;
  13678. }
  13679. this._gl.disableVertexAttribArray(i);
  13680. this._vertexAttribArraysEnabled[i] = false;
  13681. this._currentBufferPointers[i].active = false;
  13682. }
  13683. };
  13684. Engine.prototype.releaseEffects = function () {
  13685. for (var name in this._compiledEffects) {
  13686. this._deleteProgram(this._compiledEffects[name]._program);
  13687. }
  13688. this._compiledEffects = {};
  13689. };
  13690. // Dispose
  13691. Engine.prototype.dispose = function () {
  13692. this.hideLoadingUI();
  13693. this.stopRenderLoop();
  13694. // Release postProcesses
  13695. while (this.postProcesses.length) {
  13696. this.postProcesses[0].dispose();
  13697. }
  13698. // Empty texture
  13699. if (this._emptyTexture) {
  13700. this._releaseTexture(this._emptyTexture);
  13701. this._emptyTexture = null;
  13702. }
  13703. if (this._emptyCubeTexture) {
  13704. this._releaseTexture(this._emptyCubeTexture);
  13705. this._emptyCubeTexture = null;
  13706. }
  13707. // Rescale PP
  13708. if (this._rescalePostProcess) {
  13709. this._rescalePostProcess.dispose();
  13710. }
  13711. // Release scenes
  13712. while (this.scenes.length) {
  13713. this.scenes[0].dispose();
  13714. }
  13715. // Release audio engine
  13716. if (Engine.audioEngine) {
  13717. Engine.audioEngine.dispose();
  13718. }
  13719. // Release effects
  13720. this.releaseEffects();
  13721. // Unbind
  13722. this.unbindAllAttributes();
  13723. if (this._dummyFramebuffer) {
  13724. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13725. }
  13726. //WebVR
  13727. this.disableVR();
  13728. // Events
  13729. if (BABYLON.Tools.IsWindowObjectExist()) {
  13730. window.removeEventListener("blur", this._onBlur);
  13731. window.removeEventListener("focus", this._onFocus);
  13732. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13733. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13734. if (this._renderingCanvas) {
  13735. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13736. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13737. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13738. if (!this._doNotHandleContextLost) {
  13739. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13740. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13741. }
  13742. }
  13743. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13744. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13745. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13746. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13747. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13748. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13749. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13750. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13751. if (this._onVrDisplayConnect) {
  13752. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13753. if (this._onVrDisplayDisconnect) {
  13754. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13755. }
  13756. if (this._onVrDisplayPresentChange) {
  13757. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13758. }
  13759. this._onVrDisplayConnect = null;
  13760. this._onVrDisplayDisconnect = null;
  13761. }
  13762. }
  13763. // Remove from Instances
  13764. var index = Engine.Instances.indexOf(this);
  13765. if (index >= 0) {
  13766. Engine.Instances.splice(index, 1);
  13767. }
  13768. this._workingCanvas = null;
  13769. this._workingContext = null;
  13770. this._currentBufferPointers = [];
  13771. this._renderingCanvas = null;
  13772. this._currentProgram = null;
  13773. this.onResizeObservable.clear();
  13774. this.onCanvasBlurObservable.clear();
  13775. this.onCanvasFocusObservable.clear();
  13776. this.onCanvasPointerOutObservable.clear();
  13777. this.onBeginFrameObservable.clear();
  13778. this.onEndFrameObservable.clear();
  13779. BABYLON.Effect.ResetCache();
  13780. // Abort active requests
  13781. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13782. var request = _a[_i];
  13783. request.abort();
  13784. }
  13785. };
  13786. // Loading screen
  13787. Engine.prototype.displayLoadingUI = function () {
  13788. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13789. return;
  13790. }
  13791. var loadingScreen = this.loadingScreen;
  13792. if (loadingScreen) {
  13793. loadingScreen.displayLoadingUI();
  13794. }
  13795. };
  13796. Engine.prototype.hideLoadingUI = function () {
  13797. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13798. return;
  13799. }
  13800. var loadingScreen = this.loadingScreen;
  13801. if (loadingScreen) {
  13802. loadingScreen.hideLoadingUI();
  13803. }
  13804. };
  13805. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13806. get: function () {
  13807. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13808. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13809. return this._loadingScreen;
  13810. },
  13811. set: function (loadingScreen) {
  13812. this._loadingScreen = loadingScreen;
  13813. },
  13814. enumerable: true,
  13815. configurable: true
  13816. });
  13817. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13818. set: function (text) {
  13819. this.loadingScreen.loadingUIText = text;
  13820. },
  13821. enumerable: true,
  13822. configurable: true
  13823. });
  13824. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13825. set: function (color) {
  13826. this.loadingScreen.loadingUIBackgroundColor = color;
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. Engine.prototype.attachContextLostEvent = function (callback) {
  13832. if (this._renderingCanvas) {
  13833. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13834. }
  13835. };
  13836. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13837. if (this._renderingCanvas) {
  13838. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13839. }
  13840. };
  13841. Engine.prototype.getVertexShaderSource = function (program) {
  13842. var shaders = this._gl.getAttachedShaders(program);
  13843. if (!shaders) {
  13844. return null;
  13845. }
  13846. return this._gl.getShaderSource(shaders[0]);
  13847. };
  13848. Engine.prototype.getFragmentShaderSource = function (program) {
  13849. var shaders = this._gl.getAttachedShaders(program);
  13850. if (!shaders) {
  13851. return null;
  13852. }
  13853. return this._gl.getShaderSource(shaders[1]);
  13854. };
  13855. Engine.prototype.getError = function () {
  13856. return this._gl.getError();
  13857. };
  13858. // FPS
  13859. Engine.prototype.getFps = function () {
  13860. return this._fps;
  13861. };
  13862. Engine.prototype.getDeltaTime = function () {
  13863. return this._deltaTime;
  13864. };
  13865. Engine.prototype._measureFps = function () {
  13866. this._performanceMonitor.sampleFrame();
  13867. this._fps = this._performanceMonitor.averageFPS;
  13868. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13869. };
  13870. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13871. if (faceIndex === void 0) { faceIndex = -1; }
  13872. var gl = this._gl;
  13873. if (!this._dummyFramebuffer) {
  13874. var dummy = gl.createFramebuffer();
  13875. if (!dummy) {
  13876. throw new Error("Unable to create dummy framebuffer");
  13877. }
  13878. this._dummyFramebuffer = dummy;
  13879. }
  13880. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13881. if (faceIndex > -1) {
  13882. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13883. }
  13884. else {
  13885. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13886. }
  13887. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13888. var buffer;
  13889. switch (readType) {
  13890. case gl.UNSIGNED_BYTE:
  13891. buffer = new Uint8Array(4 * width * height);
  13892. readType = gl.UNSIGNED_BYTE;
  13893. break;
  13894. default:
  13895. buffer = new Float32Array(4 * width * height);
  13896. readType = gl.FLOAT;
  13897. break;
  13898. }
  13899. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13900. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13901. return buffer;
  13902. };
  13903. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13904. if (this._webGLVersion > 1) {
  13905. return this._caps.colorBufferFloat;
  13906. }
  13907. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13908. };
  13909. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13910. if (this._webGLVersion > 1) {
  13911. return this._caps.colorBufferFloat;
  13912. }
  13913. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13914. };
  13915. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13916. Engine.prototype._canRenderToFramebuffer = function (type) {
  13917. var gl = this._gl;
  13918. //clear existing errors
  13919. while (gl.getError() !== gl.NO_ERROR) { }
  13920. var successful = true;
  13921. var texture = gl.createTexture();
  13922. gl.bindTexture(gl.TEXTURE_2D, texture);
  13923. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13924. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13925. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13926. var fb = gl.createFramebuffer();
  13927. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13928. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13929. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13930. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13931. successful = successful && (gl.getError() === gl.NO_ERROR);
  13932. //try render by clearing frame buffer's color buffer
  13933. if (successful) {
  13934. gl.clear(gl.COLOR_BUFFER_BIT);
  13935. successful = successful && (gl.getError() === gl.NO_ERROR);
  13936. }
  13937. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13938. if (successful) {
  13939. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13940. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13941. var readFormat = gl.RGBA;
  13942. var readType = gl.UNSIGNED_BYTE;
  13943. var buffer = new Uint8Array(4);
  13944. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13945. successful = successful && (gl.getError() === gl.NO_ERROR);
  13946. }
  13947. //clean up
  13948. gl.deleteTexture(texture);
  13949. gl.deleteFramebuffer(fb);
  13950. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13951. //clear accumulated errors
  13952. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13953. return successful;
  13954. };
  13955. Engine.prototype._getWebGLTextureType = function (type) {
  13956. if (type === Engine.TEXTURETYPE_FLOAT) {
  13957. return this._gl.FLOAT;
  13958. }
  13959. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13960. // Add Half Float Constant.
  13961. return this._gl.HALF_FLOAT_OES;
  13962. }
  13963. return this._gl.UNSIGNED_BYTE;
  13964. };
  13965. ;
  13966. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13967. if (this._webGLVersion === 1) {
  13968. return this._gl.RGBA;
  13969. }
  13970. if (type === Engine.TEXTURETYPE_FLOAT) {
  13971. return this._gl.RGBA32F;
  13972. }
  13973. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13974. return this._gl.RGBA16F;
  13975. }
  13976. return this._gl.RGBA;
  13977. };
  13978. ;
  13979. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13980. if (type === Engine.TEXTURETYPE_FLOAT) {
  13981. return this._gl.RGBA32F;
  13982. }
  13983. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13984. return this._gl.RGBA16F;
  13985. }
  13986. return this._gl.RGBA8;
  13987. };
  13988. ;
  13989. Engine.prototype.createQuery = function () {
  13990. return this._gl.createQuery();
  13991. };
  13992. Engine.prototype.deleteQuery = function (query) {
  13993. this._gl.deleteQuery(query);
  13994. return this;
  13995. };
  13996. Engine.prototype.isQueryResultAvailable = function (query) {
  13997. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13998. };
  13999. Engine.prototype.getQueryResult = function (query) {
  14000. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14001. };
  14002. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14003. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14004. this._gl.beginQuery(glAlgorithm, query);
  14005. return this;
  14006. };
  14007. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14008. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14009. this._gl.endQuery(glAlgorithm);
  14010. return this;
  14011. };
  14012. /* Time queries */
  14013. Engine.prototype._createTimeQuery = function () {
  14014. var timerQuery = this._caps.timerQuery;
  14015. if (timerQuery.createQueryEXT) {
  14016. return timerQuery.createQueryEXT();
  14017. }
  14018. return this.createQuery();
  14019. };
  14020. Engine.prototype._deleteTimeQuery = function (query) {
  14021. var timerQuery = this._caps.timerQuery;
  14022. if (timerQuery.deleteQueryEXT) {
  14023. timerQuery.deleteQueryEXT(query);
  14024. return;
  14025. }
  14026. this.deleteQuery(query);
  14027. };
  14028. Engine.prototype._getTimeQueryResult = function (query) {
  14029. var timerQuery = this._caps.timerQuery;
  14030. if (timerQuery.getQueryObjectEXT) {
  14031. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14032. }
  14033. return this.getQueryResult(query);
  14034. };
  14035. Engine.prototype._getTimeQueryAvailability = function (query) {
  14036. var timerQuery = this._caps.timerQuery;
  14037. if (timerQuery.getQueryObjectEXT) {
  14038. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14039. }
  14040. return this.isQueryResultAvailable(query);
  14041. };
  14042. Engine.prototype.startTimeQuery = function () {
  14043. var timerQuery = this._caps.timerQuery;
  14044. if (!timerQuery) {
  14045. return null;
  14046. }
  14047. var token = new BABYLON._TimeToken();
  14048. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14049. if (this._caps.canUseTimestampForTimerQuery) {
  14050. token._startTimeQuery = this._createTimeQuery();
  14051. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14052. }
  14053. else {
  14054. if (this._currentNonTimestampToken) {
  14055. return this._currentNonTimestampToken;
  14056. }
  14057. token._timeElapsedQuery = this._createTimeQuery();
  14058. if (timerQuery.beginQueryEXT) {
  14059. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14060. }
  14061. else {
  14062. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14063. }
  14064. this._currentNonTimestampToken = token;
  14065. }
  14066. return token;
  14067. };
  14068. Engine.prototype.endTimeQuery = function (token) {
  14069. var timerQuery = this._caps.timerQuery;
  14070. if (!timerQuery || !token) {
  14071. return -1;
  14072. }
  14073. if (this._caps.canUseTimestampForTimerQuery) {
  14074. if (!token._startTimeQuery) {
  14075. return -1;
  14076. }
  14077. if (!token._endTimeQuery) {
  14078. token._endTimeQuery = this._createTimeQuery();
  14079. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14080. }
  14081. }
  14082. else if (!token._timeElapsedQueryEnded) {
  14083. if (!token._timeElapsedQuery) {
  14084. return -1;
  14085. }
  14086. if (timerQuery.endQueryEXT) {
  14087. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14088. }
  14089. else {
  14090. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14091. }
  14092. token._timeElapsedQueryEnded = true;
  14093. }
  14094. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14095. var available = false;
  14096. if (token._endTimeQuery) {
  14097. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14098. }
  14099. else if (token._timeElapsedQuery) {
  14100. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14101. }
  14102. if (available && !disjoint) {
  14103. var result = 0;
  14104. if (this._caps.canUseTimestampForTimerQuery) {
  14105. if (!token._startTimeQuery || !token._endTimeQuery) {
  14106. return -1;
  14107. }
  14108. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14109. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14110. result = timeEnd - timeStart;
  14111. this._deleteTimeQuery(token._startTimeQuery);
  14112. this._deleteTimeQuery(token._endTimeQuery);
  14113. token._startTimeQuery = null;
  14114. token._endTimeQuery = null;
  14115. }
  14116. else {
  14117. if (!token._timeElapsedQuery) {
  14118. return -1;
  14119. }
  14120. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14121. this._deleteTimeQuery(token._timeElapsedQuery);
  14122. token._timeElapsedQuery = null;
  14123. token._timeElapsedQueryEnded = false;
  14124. this._currentNonTimestampToken = null;
  14125. }
  14126. return result;
  14127. }
  14128. return -1;
  14129. };
  14130. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14131. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14132. };
  14133. // Transform feedback
  14134. Engine.prototype.createTransformFeedback = function () {
  14135. return this._gl.createTransformFeedback();
  14136. };
  14137. Engine.prototype.deleteTransformFeedback = function (value) {
  14138. this._gl.deleteTransformFeedback(value);
  14139. };
  14140. Engine.prototype.bindTransformFeedback = function (value) {
  14141. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14142. };
  14143. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14144. if (usePoints === void 0) { usePoints = true; }
  14145. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14146. };
  14147. Engine.prototype.endTransformFeedback = function () {
  14148. this._gl.endTransformFeedback();
  14149. };
  14150. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14151. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14152. };
  14153. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14154. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14155. };
  14156. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14157. var _this = this;
  14158. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14159. this._activeRequests.push(request);
  14160. request.onCompleteObservable.add(function (request) {
  14161. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14162. });
  14163. return request;
  14164. };
  14165. /** @ignore */
  14166. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14167. var _this = this;
  14168. return new Promise(function (resolve, reject) {
  14169. _this._loadFile(url, function (data) {
  14170. resolve(data);
  14171. }, undefined, database, useArrayBuffer, function (request, exception) {
  14172. reject(exception);
  14173. });
  14174. });
  14175. };
  14176. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14177. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14178. var onload = function (data) {
  14179. loadedFiles[index] = data;
  14180. loadedFiles._internalCount++;
  14181. if (loadedFiles._internalCount === 6) {
  14182. onfinish(loadedFiles);
  14183. }
  14184. };
  14185. var onerror = function (request, exception) {
  14186. if (onErrorCallBack && request) {
  14187. onErrorCallBack(request.status + " " + request.statusText, exception);
  14188. }
  14189. };
  14190. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14191. };
  14192. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14193. if (onError === void 0) { onError = null; }
  14194. var loadedFiles = [];
  14195. loadedFiles._internalCount = 0;
  14196. for (var index = 0; index < 6; index++) {
  14197. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14198. }
  14199. };
  14200. // Statics
  14201. Engine.isSupported = function () {
  14202. try {
  14203. var tempcanvas = document.createElement("canvas");
  14204. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14205. return gl != null && !!window.WebGLRenderingContext;
  14206. }
  14207. catch (e) {
  14208. return false;
  14209. }
  14210. };
  14211. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14212. Engine.ExceptionList = [
  14213. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14214. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14215. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14216. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14217. ];
  14218. Engine.Instances = new Array();
  14219. // Const statics
  14220. Engine._ALPHA_DISABLE = 0;
  14221. Engine._ALPHA_ADD = 1;
  14222. Engine._ALPHA_COMBINE = 2;
  14223. Engine._ALPHA_SUBTRACT = 3;
  14224. Engine._ALPHA_MULTIPLY = 4;
  14225. Engine._ALPHA_MAXIMIZED = 5;
  14226. Engine._ALPHA_ONEONE = 6;
  14227. Engine._ALPHA_PREMULTIPLIED = 7;
  14228. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14229. Engine._ALPHA_INTERPOLATE = 9;
  14230. Engine._ALPHA_SCREENMODE = 10;
  14231. Engine._DELAYLOADSTATE_NONE = 0;
  14232. Engine._DELAYLOADSTATE_LOADED = 1;
  14233. Engine._DELAYLOADSTATE_LOADING = 2;
  14234. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14235. Engine._TEXTUREFORMAT_ALPHA = 0;
  14236. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14237. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14238. Engine._TEXTUREFORMAT_RGB = 4;
  14239. Engine._TEXTUREFORMAT_RGBA = 5;
  14240. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14241. Engine._TEXTURETYPE_FLOAT = 1;
  14242. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14243. // Depht or Stencil test Constants.
  14244. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14245. 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.
  14246. 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.
  14247. 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.
  14248. 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.
  14249. 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.
  14250. 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.
  14251. 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.
  14252. // Stencil Actions Constants.
  14253. Engine._KEEP = 0x1E00;
  14254. Engine._REPLACE = 0x1E01;
  14255. Engine._INCR = 0x1E02;
  14256. Engine._DECR = 0x1E03;
  14257. Engine._INVERT = 0x150A;
  14258. Engine._INCR_WRAP = 0x8507;
  14259. Engine._DECR_WRAP = 0x8508;
  14260. // Texture rescaling mode
  14261. Engine._SCALEMODE_FLOOR = 1;
  14262. Engine._SCALEMODE_NEAREST = 2;
  14263. Engine._SCALEMODE_CEILING = 3;
  14264. // Updatable statics so stick with vars here
  14265. Engine.CollisionsEpsilon = 0.001;
  14266. Engine.CodeRepository = "src/";
  14267. Engine.ShadersRepository = "src/Shaders/";
  14268. return Engine;
  14269. }());
  14270. BABYLON.Engine = Engine;
  14271. })(BABYLON || (BABYLON = {}));
  14272. //# sourceMappingURL=babylon.engine.js.map
  14273. var BABYLON;
  14274. (function (BABYLON) {
  14275. /**
  14276. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14277. */
  14278. var Node = /** @class */ (function () {
  14279. /**
  14280. * @constructor
  14281. * @param {string} name - the name and id to be given to this node
  14282. * @param {BABYLON.Scene} the scene this node will be added to
  14283. */
  14284. function Node(name, scene) {
  14285. if (scene === void 0) { scene = null; }
  14286. this.state = "";
  14287. this.metadata = null;
  14288. this.doNotSerialize = false;
  14289. this.animations = new Array();
  14290. this._ranges = {};
  14291. this._isEnabled = true;
  14292. this._isReady = true;
  14293. this._currentRenderId = -1;
  14294. this._parentRenderId = -1;
  14295. /**
  14296. * An event triggered when the mesh is disposed.
  14297. * @type {BABYLON.Observable}
  14298. */
  14299. this.onDisposeObservable = new BABYLON.Observable();
  14300. // Behaviors
  14301. this._behaviors = new Array();
  14302. this.name = name;
  14303. this.id = name;
  14304. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14305. this.uniqueId = this._scene.getUniqueId();
  14306. this._initCache();
  14307. }
  14308. Object.defineProperty(Node.prototype, "parent", {
  14309. get: function () {
  14310. return this._parentNode;
  14311. },
  14312. set: function (parent) {
  14313. if (this._parentNode === parent) {
  14314. return;
  14315. }
  14316. // Remove self from list of children of parent
  14317. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14318. var index = this._parentNode._children.indexOf(this);
  14319. if (index !== -1) {
  14320. this._parentNode._children.splice(index, 1);
  14321. }
  14322. }
  14323. // Store new parent
  14324. this._parentNode = parent;
  14325. // Add as child to new parent
  14326. if (this._parentNode) {
  14327. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14328. this._parentNode._children = new Array();
  14329. }
  14330. this._parentNode._children.push(this);
  14331. }
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Node.prototype.getClassName = function () {
  14337. return "Node";
  14338. };
  14339. Object.defineProperty(Node.prototype, "onDispose", {
  14340. set: function (callback) {
  14341. if (this._onDisposeObserver) {
  14342. this.onDisposeObservable.remove(this._onDisposeObserver);
  14343. }
  14344. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14345. },
  14346. enumerable: true,
  14347. configurable: true
  14348. });
  14349. Node.prototype.getScene = function () {
  14350. return this._scene;
  14351. };
  14352. Node.prototype.getEngine = function () {
  14353. return this._scene.getEngine();
  14354. };
  14355. Node.prototype.addBehavior = function (behavior) {
  14356. var _this = this;
  14357. var index = this._behaviors.indexOf(behavior);
  14358. if (index !== -1) {
  14359. return this;
  14360. }
  14361. behavior.init();
  14362. if (this._scene.isLoading) {
  14363. // We defer the attach when the scene will be loaded
  14364. var observer = this._scene.onDataLoadedObservable.add(function () {
  14365. behavior.attach(_this);
  14366. setTimeout(function () {
  14367. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14368. _this._scene.onDataLoadedObservable.remove(observer);
  14369. }, 0);
  14370. });
  14371. }
  14372. else {
  14373. behavior.attach(this);
  14374. }
  14375. this._behaviors.push(behavior);
  14376. return this;
  14377. };
  14378. Node.prototype.removeBehavior = function (behavior) {
  14379. var index = this._behaviors.indexOf(behavior);
  14380. if (index === -1) {
  14381. return this;
  14382. }
  14383. this._behaviors[index].detach();
  14384. this._behaviors.splice(index, 1);
  14385. return this;
  14386. };
  14387. Object.defineProperty(Node.prototype, "behaviors", {
  14388. get: function () {
  14389. return this._behaviors;
  14390. },
  14391. enumerable: true,
  14392. configurable: true
  14393. });
  14394. Node.prototype.getBehaviorByName = function (name) {
  14395. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14396. var behavior = _a[_i];
  14397. if (behavior.name === name) {
  14398. return behavior;
  14399. }
  14400. }
  14401. return null;
  14402. };
  14403. // override it in derived class
  14404. Node.prototype.getWorldMatrix = function () {
  14405. return BABYLON.Matrix.Identity();
  14406. };
  14407. // override it in derived class if you add new variables to the cache
  14408. // and call the parent class method
  14409. Node.prototype._initCache = function () {
  14410. this._cache = {};
  14411. this._cache.parent = undefined;
  14412. };
  14413. Node.prototype.updateCache = function (force) {
  14414. if (!force && this.isSynchronized())
  14415. return;
  14416. this._cache.parent = this.parent;
  14417. this._updateCache();
  14418. };
  14419. // override it in derived class if you add new variables to the cache
  14420. // and call the parent class method if !ignoreParentClass
  14421. Node.prototype._updateCache = function (ignoreParentClass) {
  14422. };
  14423. // override it in derived class if you add new variables to the cache
  14424. Node.prototype._isSynchronized = function () {
  14425. return true;
  14426. };
  14427. Node.prototype._markSyncedWithParent = function () {
  14428. if (this.parent) {
  14429. this._parentRenderId = this.parent._currentRenderId;
  14430. }
  14431. };
  14432. Node.prototype.isSynchronizedWithParent = function () {
  14433. if (!this.parent) {
  14434. return true;
  14435. }
  14436. if (this._parentRenderId !== this.parent._currentRenderId) {
  14437. return false;
  14438. }
  14439. return this.parent.isSynchronized();
  14440. };
  14441. Node.prototype.isSynchronized = function (updateCache) {
  14442. var check = this.hasNewParent();
  14443. check = check || !this.isSynchronizedWithParent();
  14444. check = check || !this._isSynchronized();
  14445. if (updateCache)
  14446. this.updateCache(true);
  14447. return !check;
  14448. };
  14449. Node.prototype.hasNewParent = function (update) {
  14450. if (this._cache.parent === this.parent)
  14451. return false;
  14452. if (update)
  14453. this._cache.parent = this.parent;
  14454. return true;
  14455. };
  14456. /**
  14457. * Is this node ready to be used/rendered
  14458. * @return {boolean} is it ready
  14459. */
  14460. Node.prototype.isReady = function () {
  14461. return this._isReady;
  14462. };
  14463. /**
  14464. * Is this node enabled.
  14465. * 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.
  14466. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  14467. * @return {boolean} whether this node (and its parent) is enabled.
  14468. * @see setEnabled
  14469. */
  14470. Node.prototype.isEnabled = function (checkAncestors) {
  14471. if (checkAncestors === void 0) { checkAncestors = true; }
  14472. if (checkAncestors === false) {
  14473. return this._isEnabled;
  14474. }
  14475. if (this._isEnabled === false) {
  14476. return false;
  14477. }
  14478. if (this.parent !== undefined && this.parent !== null) {
  14479. return this.parent.isEnabled(checkAncestors);
  14480. }
  14481. return true;
  14482. };
  14483. /**
  14484. * Set the enabled state of this node.
  14485. * @param {boolean} value - the new enabled state
  14486. * @see isEnabled
  14487. */
  14488. Node.prototype.setEnabled = function (value) {
  14489. this._isEnabled = value;
  14490. };
  14491. /**
  14492. * Is this node a descendant of the given node.
  14493. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14494. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14495. * @see parent
  14496. */
  14497. Node.prototype.isDescendantOf = function (ancestor) {
  14498. if (this.parent) {
  14499. if (this.parent === ancestor) {
  14500. return true;
  14501. }
  14502. return this.parent.isDescendantOf(ancestor);
  14503. }
  14504. return false;
  14505. };
  14506. /**
  14507. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14508. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14509. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  14510. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14511. */
  14512. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14513. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14514. if (!this._children) {
  14515. return;
  14516. }
  14517. for (var index = 0; index < this._children.length; index++) {
  14518. var item = this._children[index];
  14519. if (!predicate || predicate(item)) {
  14520. results.push(item);
  14521. }
  14522. if (!directDescendantsOnly) {
  14523. item._getDescendants(results, false, predicate);
  14524. }
  14525. }
  14526. };
  14527. /**
  14528. * Will return all nodes that have this node as ascendant.
  14529. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  14530. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14531. * @return {BABYLON.Node[]} all children nodes of all types.
  14532. */
  14533. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14534. var results = new Array();
  14535. this._getDescendants(results, directDescendantsOnly, predicate);
  14536. return results;
  14537. };
  14538. /**
  14539. * Get all child-meshes of this node.
  14540. */
  14541. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14542. var results = [];
  14543. this._getDescendants(results, directDescendantsOnly, function (node) {
  14544. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14545. });
  14546. return results;
  14547. };
  14548. /**
  14549. * Get all child-transformNodes of this node.
  14550. */
  14551. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14552. var results = [];
  14553. this._getDescendants(results, directDescendantsOnly, function (node) {
  14554. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14555. });
  14556. return results;
  14557. };
  14558. /**
  14559. * Get all direct children of this node.
  14560. */
  14561. Node.prototype.getChildren = function (predicate) {
  14562. return this.getDescendants(true, predicate);
  14563. };
  14564. Node.prototype._setReady = function (state) {
  14565. if (state === this._isReady) {
  14566. return;
  14567. }
  14568. if (!state) {
  14569. this._isReady = false;
  14570. return;
  14571. }
  14572. this._isReady = true;
  14573. if (this.onReady) {
  14574. this.onReady(this);
  14575. }
  14576. };
  14577. Node.prototype.getAnimationByName = function (name) {
  14578. for (var i = 0; i < this.animations.length; i++) {
  14579. var animation = this.animations[i];
  14580. if (animation.name === name) {
  14581. return animation;
  14582. }
  14583. }
  14584. return null;
  14585. };
  14586. Node.prototype.createAnimationRange = function (name, from, to) {
  14587. // check name not already in use
  14588. if (!this._ranges[name]) {
  14589. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14590. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14591. if (this.animations[i]) {
  14592. this.animations[i].createRange(name, from, to);
  14593. }
  14594. }
  14595. }
  14596. };
  14597. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14598. if (deleteFrames === void 0) { deleteFrames = true; }
  14599. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14600. if (this.animations[i]) {
  14601. this.animations[i].deleteRange(name, deleteFrames);
  14602. }
  14603. }
  14604. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14605. };
  14606. Node.prototype.getAnimationRange = function (name) {
  14607. return this._ranges[name];
  14608. };
  14609. /**
  14610. * Will start the animation sequence
  14611. * @param name defines the range frames for animation sequence
  14612. * @param loop defines if the animation should loop (false by default)
  14613. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  14614. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  14615. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  14616. */
  14617. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14618. var range = this.getAnimationRange(name);
  14619. if (!range) {
  14620. return null;
  14621. }
  14622. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14623. };
  14624. Node.prototype.serializeAnimationRanges = function () {
  14625. var serializationRanges = [];
  14626. for (var name in this._ranges) {
  14627. var localRange = this._ranges[name];
  14628. if (!localRange) {
  14629. continue;
  14630. }
  14631. var range = {};
  14632. range.name = name;
  14633. range.from = localRange.from;
  14634. range.to = localRange.to;
  14635. serializationRanges.push(range);
  14636. }
  14637. return serializationRanges;
  14638. };
  14639. // override it in derived class
  14640. Node.prototype.computeWorldMatrix = function (force) {
  14641. return BABYLON.Matrix.Identity();
  14642. };
  14643. Node.prototype.dispose = function () {
  14644. this.parent = null;
  14645. // Callback
  14646. this.onDisposeObservable.notifyObservers(this);
  14647. this.onDisposeObservable.clear();
  14648. // Behaviors
  14649. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14650. var behavior = _a[_i];
  14651. behavior.detach();
  14652. }
  14653. this._behaviors = [];
  14654. };
  14655. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14656. if (parsedNode.ranges) {
  14657. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14658. var data = parsedNode.ranges[index];
  14659. node.createAnimationRange(data.name, data.from, data.to);
  14660. }
  14661. }
  14662. };
  14663. __decorate([
  14664. BABYLON.serialize()
  14665. ], Node.prototype, "name", void 0);
  14666. __decorate([
  14667. BABYLON.serialize()
  14668. ], Node.prototype, "id", void 0);
  14669. __decorate([
  14670. BABYLON.serialize()
  14671. ], Node.prototype, "uniqueId", void 0);
  14672. __decorate([
  14673. BABYLON.serialize()
  14674. ], Node.prototype, "state", void 0);
  14675. __decorate([
  14676. BABYLON.serialize()
  14677. ], Node.prototype, "metadata", void 0);
  14678. return Node;
  14679. }());
  14680. BABYLON.Node = Node;
  14681. })(BABYLON || (BABYLON = {}));
  14682. //# sourceMappingURL=babylon.node.js.map
  14683. var BABYLON;
  14684. (function (BABYLON) {
  14685. var BoundingSphere = /** @class */ (function () {
  14686. function BoundingSphere(minimum, maximum) {
  14687. this.minimum = minimum;
  14688. this.maximum = maximum;
  14689. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14690. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14691. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14692. this.radius = distance * 0.5;
  14693. this.centerWorld = BABYLON.Vector3.Zero();
  14694. this._update(BABYLON.Matrix.Identity());
  14695. }
  14696. // Methods
  14697. BoundingSphere.prototype._update = function (world) {
  14698. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14699. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14700. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14701. };
  14702. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14703. for (var i = 0; i < 6; i++) {
  14704. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14705. return false;
  14706. }
  14707. return true;
  14708. };
  14709. BoundingSphere.prototype.intersectsPoint = function (point) {
  14710. var x = this.centerWorld.x - point.x;
  14711. var y = this.centerWorld.y - point.y;
  14712. var z = this.centerWorld.z - point.z;
  14713. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14714. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14715. return false;
  14716. return true;
  14717. };
  14718. // Statics
  14719. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14720. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14721. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14722. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14723. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14724. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14725. return false;
  14726. return true;
  14727. };
  14728. return BoundingSphere;
  14729. }());
  14730. BABYLON.BoundingSphere = BoundingSphere;
  14731. })(BABYLON || (BABYLON = {}));
  14732. //# sourceMappingURL=babylon.boundingSphere.js.map
  14733. var BABYLON;
  14734. (function (BABYLON) {
  14735. var BoundingBox = /** @class */ (function () {
  14736. function BoundingBox(minimum, maximum) {
  14737. this.minimum = minimum;
  14738. this.maximum = maximum;
  14739. this.vectors = new Array();
  14740. this.vectorsWorld = new Array();
  14741. // Bounding vectors
  14742. this.vectors.push(this.minimum.clone());
  14743. this.vectors.push(this.maximum.clone());
  14744. this.vectors.push(this.minimum.clone());
  14745. this.vectors[2].x = this.maximum.x;
  14746. this.vectors.push(this.minimum.clone());
  14747. this.vectors[3].y = this.maximum.y;
  14748. this.vectors.push(this.minimum.clone());
  14749. this.vectors[4].z = this.maximum.z;
  14750. this.vectors.push(this.maximum.clone());
  14751. this.vectors[5].z = this.minimum.z;
  14752. this.vectors.push(this.maximum.clone());
  14753. this.vectors[6].x = this.minimum.x;
  14754. this.vectors.push(this.maximum.clone());
  14755. this.vectors[7].y = this.minimum.y;
  14756. // OBB
  14757. this.center = this.maximum.add(this.minimum).scale(0.5);
  14758. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14759. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14760. // World
  14761. for (var index = 0; index < this.vectors.length; index++) {
  14762. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14763. }
  14764. this.minimumWorld = BABYLON.Vector3.Zero();
  14765. this.maximumWorld = BABYLON.Vector3.Zero();
  14766. this.centerWorld = BABYLON.Vector3.Zero();
  14767. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14768. this._update(BABYLON.Matrix.Identity());
  14769. }
  14770. // Methods
  14771. BoundingBox.prototype.getWorldMatrix = function () {
  14772. return this._worldMatrix;
  14773. };
  14774. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14775. this._worldMatrix.copyFrom(matrix);
  14776. return this;
  14777. };
  14778. BoundingBox.prototype._update = function (world) {
  14779. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14780. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14781. for (var index = 0; index < this.vectors.length; index++) {
  14782. var v = this.vectorsWorld[index];
  14783. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14784. if (v.x < this.minimumWorld.x)
  14785. this.minimumWorld.x = v.x;
  14786. if (v.y < this.minimumWorld.y)
  14787. this.minimumWorld.y = v.y;
  14788. if (v.z < this.minimumWorld.z)
  14789. this.minimumWorld.z = v.z;
  14790. if (v.x > this.maximumWorld.x)
  14791. this.maximumWorld.x = v.x;
  14792. if (v.y > this.maximumWorld.y)
  14793. this.maximumWorld.y = v.y;
  14794. if (v.z > this.maximumWorld.z)
  14795. this.maximumWorld.z = v.z;
  14796. }
  14797. // Extend
  14798. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14799. this.extendSizeWorld.scaleInPlace(0.5);
  14800. // OBB
  14801. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14802. this.centerWorld.scaleInPlace(0.5);
  14803. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14804. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14805. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14806. this._worldMatrix = world;
  14807. };
  14808. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14809. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14810. };
  14811. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14812. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14813. };
  14814. BoundingBox.prototype.intersectsPoint = function (point) {
  14815. var delta = -BABYLON.Epsilon;
  14816. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14817. return false;
  14818. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14819. return false;
  14820. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14821. return false;
  14822. return true;
  14823. };
  14824. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14825. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14826. };
  14827. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14828. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14829. return false;
  14830. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14831. return false;
  14832. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14833. return false;
  14834. return true;
  14835. };
  14836. // Statics
  14837. BoundingBox.Intersects = function (box0, box1) {
  14838. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14839. return false;
  14840. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14841. return false;
  14842. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14843. return false;
  14844. return true;
  14845. };
  14846. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14847. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14848. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14849. return (num <= (sphereRadius * sphereRadius));
  14850. };
  14851. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14852. for (var p = 0; p < 6; p++) {
  14853. for (var i = 0; i < 8; i++) {
  14854. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14855. return false;
  14856. }
  14857. }
  14858. }
  14859. return true;
  14860. };
  14861. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14862. for (var p = 0; p < 6; p++) {
  14863. var inCount = 8;
  14864. for (var i = 0; i < 8; i++) {
  14865. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14866. --inCount;
  14867. }
  14868. else {
  14869. break;
  14870. }
  14871. }
  14872. if (inCount === 0)
  14873. return false;
  14874. }
  14875. return true;
  14876. };
  14877. return BoundingBox;
  14878. }());
  14879. BABYLON.BoundingBox = BoundingBox;
  14880. })(BABYLON || (BABYLON = {}));
  14881. //# sourceMappingURL=babylon.boundingBox.js.map
  14882. var BABYLON;
  14883. (function (BABYLON) {
  14884. var computeBoxExtents = function (axis, box) {
  14885. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14886. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14887. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14888. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14889. var r = r0 + r1 + r2;
  14890. return {
  14891. min: p - r,
  14892. max: p + r
  14893. };
  14894. };
  14895. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14896. var axisOverlap = function (axis, box0, box1) {
  14897. var result0 = computeBoxExtents(axis, box0);
  14898. var result1 = computeBoxExtents(axis, box1);
  14899. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14900. };
  14901. var BoundingInfo = /** @class */ (function () {
  14902. function BoundingInfo(minimum, maximum) {
  14903. this.minimum = minimum;
  14904. this.maximum = maximum;
  14905. this._isLocked = false;
  14906. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14907. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14908. }
  14909. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14910. get: function () {
  14911. return this._isLocked;
  14912. },
  14913. set: function (value) {
  14914. this._isLocked = value;
  14915. },
  14916. enumerable: true,
  14917. configurable: true
  14918. });
  14919. // Methods
  14920. BoundingInfo.prototype.update = function (world) {
  14921. if (this._isLocked) {
  14922. return;
  14923. }
  14924. this.boundingBox._update(world);
  14925. this.boundingSphere._update(world);
  14926. };
  14927. /**
  14928. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14929. * @param center New center of the bounding info
  14930. * @param extend New extend of the bounding info
  14931. */
  14932. BoundingInfo.prototype.centerOn = function (center, extend) {
  14933. this.minimum = center.subtract(extend);
  14934. this.maximum = center.add(extend);
  14935. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14936. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14937. return this;
  14938. };
  14939. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14940. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14941. return false;
  14942. return this.boundingBox.isInFrustum(frustumPlanes);
  14943. };
  14944. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14945. /**
  14946. * Gets the world distance between the min and max points of the bounding box
  14947. */
  14948. get: function () {
  14949. var boundingBox = this.boundingBox;
  14950. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14951. return size.length();
  14952. },
  14953. enumerable: true,
  14954. configurable: true
  14955. });
  14956. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14957. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14958. };
  14959. BoundingInfo.prototype._checkCollision = function (collider) {
  14960. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14961. };
  14962. BoundingInfo.prototype.intersectsPoint = function (point) {
  14963. if (!this.boundingSphere.centerWorld) {
  14964. return false;
  14965. }
  14966. if (!this.boundingSphere.intersectsPoint(point)) {
  14967. return false;
  14968. }
  14969. if (!this.boundingBox.intersectsPoint(point)) {
  14970. return false;
  14971. }
  14972. return true;
  14973. };
  14974. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14975. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14976. return false;
  14977. }
  14978. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14979. return false;
  14980. }
  14981. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14982. return false;
  14983. }
  14984. if (!precise) {
  14985. return true;
  14986. }
  14987. var box0 = this.boundingBox;
  14988. var box1 = boundingInfo.boundingBox;
  14989. if (!axisOverlap(box0.directions[0], box0, box1))
  14990. return false;
  14991. if (!axisOverlap(box0.directions[1], box0, box1))
  14992. return false;
  14993. if (!axisOverlap(box0.directions[2], box0, box1))
  14994. return false;
  14995. if (!axisOverlap(box1.directions[0], box0, box1))
  14996. return false;
  14997. if (!axisOverlap(box1.directions[1], box0, box1))
  14998. return false;
  14999. if (!axisOverlap(box1.directions[2], box0, box1))
  15000. return false;
  15001. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15002. return false;
  15003. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15004. return false;
  15005. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15006. return false;
  15007. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15008. return false;
  15009. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15010. return false;
  15011. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15012. return false;
  15013. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15014. return false;
  15015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15016. return false;
  15017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15018. return false;
  15019. return true;
  15020. };
  15021. return BoundingInfo;
  15022. }());
  15023. BABYLON.BoundingInfo = BoundingInfo;
  15024. })(BABYLON || (BABYLON = {}));
  15025. //# sourceMappingURL=babylon.boundingInfo.js.map
  15026. var BABYLON;
  15027. (function (BABYLON) {
  15028. var TransformNode = /** @class */ (function (_super) {
  15029. __extends(TransformNode, _super);
  15030. function TransformNode(name, scene, isPure) {
  15031. if (scene === void 0) { scene = null; }
  15032. if (isPure === void 0) { isPure = true; }
  15033. var _this = _super.call(this, name, scene) || this;
  15034. // Properties
  15035. _this._rotation = BABYLON.Vector3.Zero();
  15036. _this._scaling = BABYLON.Vector3.One();
  15037. _this._isDirty = false;
  15038. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15039. _this.scalingDeterminant = 1;
  15040. _this.infiniteDistance = false;
  15041. _this.position = BABYLON.Vector3.Zero();
  15042. _this._localWorld = BABYLON.Matrix.Zero();
  15043. _this._worldMatrix = BABYLON.Matrix.Zero();
  15044. _this._worldMatrixDeterminant = 0;
  15045. _this._absolutePosition = BABYLON.Vector3.Zero();
  15046. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15047. _this._postMultiplyPivotMatrix = false;
  15048. _this._isWorldMatrixFrozen = false;
  15049. /**
  15050. * An event triggered after the world matrix is updated
  15051. * @type {BABYLON.Observable}
  15052. */
  15053. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15054. _this._nonUniformScaling = false;
  15055. if (isPure) {
  15056. _this.getScene().addTransformNode(_this);
  15057. }
  15058. return _this;
  15059. }
  15060. Object.defineProperty(TransformNode.prototype, "rotation", {
  15061. /**
  15062. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15063. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15064. * Default : (0.0, 0.0, 0.0)
  15065. */
  15066. get: function () {
  15067. return this._rotation;
  15068. },
  15069. set: function (newRotation) {
  15070. this._rotation = newRotation;
  15071. },
  15072. enumerable: true,
  15073. configurable: true
  15074. });
  15075. Object.defineProperty(TransformNode.prototype, "scaling", {
  15076. /**
  15077. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15078. * Default : (1.0, 1.0, 1.0)
  15079. */
  15080. get: function () {
  15081. return this._scaling;
  15082. },
  15083. /**
  15084. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15085. * Default : (1.0, 1.0, 1.0)
  15086. */
  15087. set: function (newScaling) {
  15088. this._scaling = newScaling;
  15089. },
  15090. enumerable: true,
  15091. configurable: true
  15092. });
  15093. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15094. /**
  15095. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15096. * It's null by default.
  15097. * 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)
  15098. */
  15099. get: function () {
  15100. return this._rotationQuaternion;
  15101. },
  15102. set: function (quaternion) {
  15103. this._rotationQuaternion = quaternion;
  15104. //reset the rotation vector.
  15105. if (quaternion && this.rotation.length()) {
  15106. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15107. }
  15108. },
  15109. enumerable: true,
  15110. configurable: true
  15111. });
  15112. /**
  15113. * Returns the latest update of the World matrix
  15114. * Returns a Matrix.
  15115. */
  15116. TransformNode.prototype.getWorldMatrix = function () {
  15117. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15118. this.computeWorldMatrix();
  15119. }
  15120. return this._worldMatrix;
  15121. };
  15122. /**
  15123. * Returns the latest update of the World matrix determinant.
  15124. */
  15125. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15126. return this._worldMatrixDeterminant;
  15127. };
  15128. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15129. /**
  15130. * Returns directly the latest state of the mesh World matrix.
  15131. * A Matrix is returned.
  15132. */
  15133. get: function () {
  15134. return this._worldMatrix;
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. /**
  15140. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15141. * Returns the AbstractMesh.
  15142. */
  15143. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15144. this._poseMatrix.copyFrom(matrix);
  15145. return this;
  15146. };
  15147. /**
  15148. * Returns the mesh Pose matrix.
  15149. * Returned object : Matrix
  15150. */
  15151. TransformNode.prototype.getPoseMatrix = function () {
  15152. return this._poseMatrix;
  15153. };
  15154. TransformNode.prototype._isSynchronized = function () {
  15155. if (this._isDirty) {
  15156. return false;
  15157. }
  15158. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15159. return false;
  15160. if (this._cache.pivotMatrixUpdated) {
  15161. return false;
  15162. }
  15163. if (this.infiniteDistance) {
  15164. return false;
  15165. }
  15166. if (!this._cache.position.equals(this.position))
  15167. return false;
  15168. if (this.rotationQuaternion) {
  15169. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15170. return false;
  15171. }
  15172. if (!this._cache.rotation.equals(this.rotation))
  15173. return false;
  15174. if (!this._cache.scaling.equals(this.scaling))
  15175. return false;
  15176. return true;
  15177. };
  15178. TransformNode.prototype._initCache = function () {
  15179. _super.prototype._initCache.call(this);
  15180. this._cache.localMatrixUpdated = false;
  15181. this._cache.position = BABYLON.Vector3.Zero();
  15182. this._cache.scaling = BABYLON.Vector3.Zero();
  15183. this._cache.rotation = BABYLON.Vector3.Zero();
  15184. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15185. this._cache.billboardMode = -1;
  15186. };
  15187. TransformNode.prototype.markAsDirty = function (property) {
  15188. if (property === "rotation") {
  15189. this.rotationQuaternion = null;
  15190. }
  15191. this._currentRenderId = Number.MAX_VALUE;
  15192. this._isDirty = true;
  15193. return this;
  15194. };
  15195. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15196. /**
  15197. * Returns the current mesh absolute position.
  15198. * Retuns a Vector3.
  15199. */
  15200. get: function () {
  15201. return this._absolutePosition;
  15202. },
  15203. enumerable: true,
  15204. configurable: true
  15205. });
  15206. /**
  15207. * Sets a new matrix to apply before all other transformation
  15208. * @param matrix defines the transform matrix
  15209. * @returns the current TransformNode
  15210. */
  15211. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15212. return this.setPivotMatrix(matrix, false);
  15213. };
  15214. /**
  15215. * Sets a new pivot matrix to the current node
  15216. * @param matrix defines the new pivot matrix to use
  15217. * @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
  15218. * @returns the current TransformNode
  15219. */
  15220. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15221. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15222. this._pivotMatrix = matrix.clone();
  15223. this._cache.pivotMatrixUpdated = true;
  15224. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15225. if (this._postMultiplyPivotMatrix) {
  15226. if (!this._pivotMatrixInverse) {
  15227. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15228. }
  15229. else {
  15230. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15231. }
  15232. }
  15233. return this;
  15234. };
  15235. /**
  15236. * Returns the mesh pivot matrix.
  15237. * Default : Identity.
  15238. * A Matrix is returned.
  15239. */
  15240. TransformNode.prototype.getPivotMatrix = function () {
  15241. return this._pivotMatrix;
  15242. };
  15243. /**
  15244. * Prevents the World matrix to be computed any longer.
  15245. * Returns the AbstractMesh.
  15246. */
  15247. TransformNode.prototype.freezeWorldMatrix = function () {
  15248. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15249. this.computeWorldMatrix(true);
  15250. this._isWorldMatrixFrozen = true;
  15251. return this;
  15252. };
  15253. /**
  15254. * Allows back the World matrix computation.
  15255. * Returns the AbstractMesh.
  15256. */
  15257. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15258. this._isWorldMatrixFrozen = false;
  15259. this.computeWorldMatrix(true);
  15260. return this;
  15261. };
  15262. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15263. /**
  15264. * True if the World matrix has been frozen.
  15265. * Returns a boolean.
  15266. */
  15267. get: function () {
  15268. return this._isWorldMatrixFrozen;
  15269. },
  15270. enumerable: true,
  15271. configurable: true
  15272. });
  15273. /**
  15274. * Retuns the mesh absolute position in the World.
  15275. * Returns a Vector3.
  15276. */
  15277. TransformNode.prototype.getAbsolutePosition = function () {
  15278. this.computeWorldMatrix();
  15279. return this._absolutePosition;
  15280. };
  15281. /**
  15282. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15283. * Returns the AbstractMesh.
  15284. */
  15285. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15286. if (!absolutePosition) {
  15287. return this;
  15288. }
  15289. var absolutePositionX;
  15290. var absolutePositionY;
  15291. var absolutePositionZ;
  15292. if (absolutePosition.x === undefined) {
  15293. if (arguments.length < 3) {
  15294. return this;
  15295. }
  15296. absolutePositionX = arguments[0];
  15297. absolutePositionY = arguments[1];
  15298. absolutePositionZ = arguments[2];
  15299. }
  15300. else {
  15301. absolutePositionX = absolutePosition.x;
  15302. absolutePositionY = absolutePosition.y;
  15303. absolutePositionZ = absolutePosition.z;
  15304. }
  15305. if (this.parent) {
  15306. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15307. invertParentWorldMatrix.invert();
  15308. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15309. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15310. }
  15311. else {
  15312. this.position.x = absolutePositionX;
  15313. this.position.y = absolutePositionY;
  15314. this.position.z = absolutePositionZ;
  15315. }
  15316. return this;
  15317. };
  15318. /**
  15319. * Sets the mesh position in its local space.
  15320. * Returns the AbstractMesh.
  15321. */
  15322. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15323. this.computeWorldMatrix();
  15324. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15325. return this;
  15326. };
  15327. /**
  15328. * Returns the mesh position in the local space from the current World matrix values.
  15329. * Returns a new Vector3.
  15330. */
  15331. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15332. this.computeWorldMatrix();
  15333. var invLocalWorldMatrix = this._localWorld.clone();
  15334. invLocalWorldMatrix.invert();
  15335. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15336. };
  15337. /**
  15338. * Translates the mesh along the passed Vector3 in its local space.
  15339. * Returns the AbstractMesh.
  15340. */
  15341. TransformNode.prototype.locallyTranslate = function (vector3) {
  15342. this.computeWorldMatrix(true);
  15343. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15344. return this;
  15345. };
  15346. /**
  15347. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15348. * @param targetPoint the position (must be in same space as current mesh) to look at
  15349. * @param yawCor optional yaw (y-axis) correction in radians
  15350. * @param pitchCor optional pitch (x-axis) correction in radians
  15351. * @param rollCor optional roll (z-axis) correction in radians
  15352. * @param space the choosen space of the target
  15353. * @returns the TransformNode.
  15354. */
  15355. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15356. if (yawCor === void 0) { yawCor = 0; }
  15357. if (pitchCor === void 0) { pitchCor = 0; }
  15358. if (rollCor === void 0) { rollCor = 0; }
  15359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15360. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15361. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15362. targetPoint.subtractToRef(pos, dv);
  15363. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15364. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15365. var pitch = Math.atan2(dv.y, len);
  15366. if (this.rotationQuaternion) {
  15367. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15368. }
  15369. else {
  15370. this.rotation.x = pitch + pitchCor;
  15371. this.rotation.y = yaw + yawCor;
  15372. this.rotation.z = rollCor;
  15373. }
  15374. return this;
  15375. };
  15376. /**
  15377. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15378. * This Vector3 is expressed in the World space.
  15379. */
  15380. TransformNode.prototype.getDirection = function (localAxis) {
  15381. var result = BABYLON.Vector3.Zero();
  15382. this.getDirectionToRef(localAxis, result);
  15383. return result;
  15384. };
  15385. /**
  15386. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15387. * localAxis is expressed in the mesh local space.
  15388. * result is computed in the Wordl space from the mesh World matrix.
  15389. * Returns the AbstractMesh.
  15390. */
  15391. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15392. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15393. return this;
  15394. };
  15395. /**
  15396. * Sets a new pivot point to the current node
  15397. * @param point defines the new pivot point to use
  15398. * @param space defines if the point is in world or local space (local by default)
  15399. * @returns the current TransformNode
  15400. */
  15401. TransformNode.prototype.setPivotPoint = function (point, space) {
  15402. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15403. if (this.getScene().getRenderId() == 0) {
  15404. this.computeWorldMatrix(true);
  15405. }
  15406. var wm = this.getWorldMatrix();
  15407. if (space == BABYLON.Space.WORLD) {
  15408. var tmat = BABYLON.Tmp.Matrix[0];
  15409. wm.invertToRef(tmat);
  15410. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15411. }
  15412. return this.setPivotMatrix(BABYLON.Matrix.Translation(point.x, point.y, point.z), true);
  15413. };
  15414. /**
  15415. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15416. */
  15417. TransformNode.prototype.getPivotPoint = function () {
  15418. var point = BABYLON.Vector3.Zero();
  15419. this.getPivotPointToRef(point);
  15420. return point;
  15421. };
  15422. /**
  15423. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15424. * Returns the AbstractMesh.
  15425. */
  15426. TransformNode.prototype.getPivotPointToRef = function (result) {
  15427. result.x = -this._pivotMatrix.m[12];
  15428. result.y = -this._pivotMatrix.m[13];
  15429. result.z = -this._pivotMatrix.m[14];
  15430. return this;
  15431. };
  15432. /**
  15433. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15434. */
  15435. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15436. var point = BABYLON.Vector3.Zero();
  15437. this.getAbsolutePivotPointToRef(point);
  15438. return point;
  15439. };
  15440. /**
  15441. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15442. * Returns the AbstractMesh.
  15443. */
  15444. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15445. result.x = this._pivotMatrix.m[12];
  15446. result.y = this._pivotMatrix.m[13];
  15447. result.z = this._pivotMatrix.m[14];
  15448. this.getPivotPointToRef(result);
  15449. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15450. return this;
  15451. };
  15452. /**
  15453. * Defines the passed node as the parent of the current node.
  15454. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15455. * Returns the TransformNode.
  15456. */
  15457. TransformNode.prototype.setParent = function (node) {
  15458. if (node === null) {
  15459. var rotation = BABYLON.Tmp.Quaternion[0];
  15460. var position = BABYLON.Tmp.Vector3[0];
  15461. var scale = BABYLON.Tmp.Vector3[1];
  15462. if (this.parent && this.parent.computeWorldMatrix) {
  15463. this.parent.computeWorldMatrix(true);
  15464. }
  15465. this.computeWorldMatrix(true);
  15466. this.getWorldMatrix().decompose(scale, rotation, position);
  15467. if (this.rotationQuaternion) {
  15468. this.rotationQuaternion.copyFrom(rotation);
  15469. }
  15470. else {
  15471. rotation.toEulerAnglesToRef(this.rotation);
  15472. }
  15473. this.scaling.x = scale.x;
  15474. this.scaling.y = scale.y;
  15475. this.scaling.z = scale.z;
  15476. this.position.x = position.x;
  15477. this.position.y = position.y;
  15478. this.position.z = position.z;
  15479. }
  15480. else {
  15481. var rotation = BABYLON.Tmp.Quaternion[0];
  15482. var position = BABYLON.Tmp.Vector3[0];
  15483. var scale = BABYLON.Tmp.Vector3[1];
  15484. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15485. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15486. this.computeWorldMatrix(true);
  15487. node.computeWorldMatrix(true);
  15488. node.getWorldMatrix().invertToRef(invParentMatrix);
  15489. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15490. diffMatrix.decompose(scale, rotation, position);
  15491. if (this.rotationQuaternion) {
  15492. this.rotationQuaternion.copyFrom(rotation);
  15493. }
  15494. else {
  15495. rotation.toEulerAnglesToRef(this.rotation);
  15496. }
  15497. this.position.x = position.x;
  15498. this.position.y = position.y;
  15499. this.position.z = position.z;
  15500. this.scaling.x = scale.x;
  15501. this.scaling.y = scale.y;
  15502. this.scaling.z = scale.z;
  15503. }
  15504. this.parent = node;
  15505. return this;
  15506. };
  15507. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15508. get: function () {
  15509. return this._nonUniformScaling;
  15510. },
  15511. enumerable: true,
  15512. configurable: true
  15513. });
  15514. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15515. if (this._nonUniformScaling === value) {
  15516. return false;
  15517. }
  15518. this._nonUniformScaling = true;
  15519. return true;
  15520. };
  15521. /**
  15522. * Attach the current TransformNode to another TransformNode associated with a bone
  15523. * @param bone Bone affecting the TransformNode
  15524. * @param affectedTransformNode TransformNode associated with the bone
  15525. */
  15526. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15527. this._transformToBoneReferal = affectedTransformNode;
  15528. this.parent = bone;
  15529. if (bone.getWorldMatrix().determinant() < 0) {
  15530. this.scalingDeterminant *= -1;
  15531. }
  15532. return this;
  15533. };
  15534. TransformNode.prototype.detachFromBone = function () {
  15535. if (!this.parent) {
  15536. return this;
  15537. }
  15538. if (this.parent.getWorldMatrix().determinant() < 0) {
  15539. this.scalingDeterminant *= -1;
  15540. }
  15541. this._transformToBoneReferal = null;
  15542. this.parent = null;
  15543. return this;
  15544. };
  15545. /**
  15546. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15547. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15548. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15549. * The passed axis is also normalized.
  15550. * Returns the AbstractMesh.
  15551. */
  15552. TransformNode.prototype.rotate = function (axis, amount, space) {
  15553. axis.normalize();
  15554. if (!this.rotationQuaternion) {
  15555. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15556. this.rotation = BABYLON.Vector3.Zero();
  15557. }
  15558. var rotationQuaternion;
  15559. if (!space || space === BABYLON.Space.LOCAL) {
  15560. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15561. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15562. }
  15563. else {
  15564. if (this.parent) {
  15565. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15566. invertParentWorldMatrix.invert();
  15567. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15568. }
  15569. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15570. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15571. }
  15572. return this;
  15573. };
  15574. /**
  15575. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15576. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15577. * The passed axis is also normalized.
  15578. * Returns the AbstractMesh.
  15579. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15580. */
  15581. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15582. axis.normalize();
  15583. if (!this.rotationQuaternion) {
  15584. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15585. this.rotation.copyFromFloats(0, 0, 0);
  15586. }
  15587. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15588. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15589. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15590. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15591. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15592. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15593. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15594. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15595. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15596. return this;
  15597. };
  15598. /**
  15599. * Translates the mesh along the axis vector for the passed distance in the given space.
  15600. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15601. * Returns the AbstractMesh.
  15602. */
  15603. TransformNode.prototype.translate = function (axis, distance, space) {
  15604. var displacementVector = axis.scale(distance);
  15605. if (!space || space === BABYLON.Space.LOCAL) {
  15606. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15607. this.setPositionWithLocalVector(tempV3);
  15608. }
  15609. else {
  15610. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15611. }
  15612. return this;
  15613. };
  15614. /**
  15615. * Adds a rotation step to the mesh current rotation.
  15616. * x, y, z are Euler angles expressed in radians.
  15617. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15618. * This means this rotation is made in the mesh local space only.
  15619. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15620. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15621. * ```javascript
  15622. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15623. * ```
  15624. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15625. * 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.
  15626. * Returns the AbstractMesh.
  15627. */
  15628. TransformNode.prototype.addRotation = function (x, y, z) {
  15629. var rotationQuaternion;
  15630. if (this.rotationQuaternion) {
  15631. rotationQuaternion = this.rotationQuaternion;
  15632. }
  15633. else {
  15634. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15635. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15636. }
  15637. var accumulation = BABYLON.Tmp.Quaternion[0];
  15638. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15639. rotationQuaternion.multiplyInPlace(accumulation);
  15640. if (!this.rotationQuaternion) {
  15641. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15642. }
  15643. return this;
  15644. };
  15645. /**
  15646. * Computes the mesh World matrix and returns it.
  15647. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15648. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15649. * If the parameter `force`is set to `true`, the actual computation is done.
  15650. * Returns the mesh World Matrix.
  15651. */
  15652. TransformNode.prototype.computeWorldMatrix = function (force) {
  15653. if (this._isWorldMatrixFrozen) {
  15654. return this._worldMatrix;
  15655. }
  15656. if (!force && this.isSynchronized(true)) {
  15657. return this._worldMatrix;
  15658. }
  15659. this._cache.position.copyFrom(this.position);
  15660. this._cache.scaling.copyFrom(this.scaling);
  15661. this._cache.pivotMatrixUpdated = false;
  15662. this._cache.billboardMode = this.billboardMode;
  15663. this._currentRenderId = this.getScene().getRenderId();
  15664. this._isDirty = false;
  15665. // Scaling
  15666. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15667. // Rotation
  15668. //rotate, if quaternion is set and rotation was used
  15669. if (this.rotationQuaternion) {
  15670. var len = this.rotation.length();
  15671. if (len) {
  15672. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15673. this.rotation.copyFromFloats(0, 0, 0);
  15674. }
  15675. }
  15676. if (this.rotationQuaternion) {
  15677. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15678. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15679. }
  15680. else {
  15681. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15682. this._cache.rotation.copyFrom(this.rotation);
  15683. }
  15684. // Translation
  15685. var camera = this.getScene().activeCamera;
  15686. if (this.infiniteDistance && !this.parent && camera) {
  15687. var cameraWorldMatrix = camera.getWorldMatrix();
  15688. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15689. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15690. }
  15691. else {
  15692. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15693. }
  15694. // Composing transformations
  15695. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15696. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15697. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15698. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15699. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15700. // Need to decompose each rotation here
  15701. var currentPosition = BABYLON.Tmp.Vector3[3];
  15702. if (this.parent && this.parent.getWorldMatrix) {
  15703. if (this._transformToBoneReferal) {
  15704. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15705. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15706. }
  15707. else {
  15708. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15709. }
  15710. }
  15711. else {
  15712. currentPosition.copyFrom(this.position);
  15713. }
  15714. currentPosition.subtractInPlace(camera.globalPosition);
  15715. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15716. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15717. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15718. }
  15719. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15720. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15721. }
  15722. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15723. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15724. }
  15725. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15726. }
  15727. else {
  15728. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15729. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15730. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15731. }
  15732. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15733. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15734. }
  15735. // Local world
  15736. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15737. // Parent
  15738. if (this.parent && this.parent.getWorldMatrix) {
  15739. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15740. if (this._transformToBoneReferal) {
  15741. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15742. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15743. }
  15744. else {
  15745. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15746. }
  15747. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15748. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15749. this._worldMatrix.copyFrom(this._localWorld);
  15750. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15751. }
  15752. else {
  15753. if (this._transformToBoneReferal) {
  15754. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15755. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15756. }
  15757. else {
  15758. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15759. }
  15760. }
  15761. this._markSyncedWithParent();
  15762. }
  15763. else {
  15764. this._worldMatrix.copyFrom(this._localWorld);
  15765. }
  15766. // Post multiply inverse of pivotMatrix
  15767. if (this._postMultiplyPivotMatrix) {
  15768. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15769. }
  15770. // Normal matrix
  15771. if (this.scaling.isNonUniform) {
  15772. this._updateNonUniformScalingState(true);
  15773. }
  15774. else if (this.parent && this.parent._nonUniformScaling) {
  15775. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15776. }
  15777. else {
  15778. this._updateNonUniformScalingState(false);
  15779. }
  15780. this._afterComputeWorldMatrix();
  15781. // Absolute position
  15782. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15783. // Callbacks
  15784. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15785. if (!this._poseMatrix) {
  15786. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15787. }
  15788. // Cache the determinant
  15789. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15790. return this._worldMatrix;
  15791. };
  15792. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15793. };
  15794. /**
  15795. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15796. * @param func: callback function to add
  15797. *
  15798. * Returns the TransformNode.
  15799. */
  15800. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15801. this.onAfterWorldMatrixUpdateObservable.add(func);
  15802. return this;
  15803. };
  15804. /**
  15805. * Removes a registered callback function.
  15806. * Returns the TransformNode.
  15807. */
  15808. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15809. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15810. return this;
  15811. };
  15812. /**
  15813. * Clone the current transform node
  15814. * Returns the new transform node
  15815. * @param name Name of the new clone
  15816. * @param newParent New parent for the clone
  15817. * @param doNotCloneChildren Do not clone children hierarchy
  15818. */
  15819. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15820. var _this = this;
  15821. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15822. result.name = name;
  15823. result.id = name;
  15824. if (newParent) {
  15825. result.parent = newParent;
  15826. }
  15827. if (!doNotCloneChildren) {
  15828. // Children
  15829. var directDescendants = this.getDescendants(true);
  15830. for (var index = 0; index < directDescendants.length; index++) {
  15831. var child = directDescendants[index];
  15832. if (child.clone) {
  15833. child.clone(name + "." + child.name, result);
  15834. }
  15835. }
  15836. }
  15837. return result;
  15838. };
  15839. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15840. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15841. serializationObject.type = this.getClassName();
  15842. // Parent
  15843. if (this.parent) {
  15844. serializationObject.parentId = this.parent.id;
  15845. }
  15846. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15847. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15848. }
  15849. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15850. serializationObject.isEnabled = this.isEnabled();
  15851. // Parent
  15852. if (this.parent) {
  15853. serializationObject.parentId = this.parent.id;
  15854. }
  15855. return serializationObject;
  15856. };
  15857. // Statics
  15858. /**
  15859. * Returns a new TransformNode object parsed from the source provided.
  15860. * The parameter `parsedMesh` is the source.
  15861. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15862. */
  15863. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15864. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15865. if (BABYLON.Tags) {
  15866. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15867. }
  15868. if (parsedTransformNode.localMatrix) {
  15869. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15870. }
  15871. else if (parsedTransformNode.pivotMatrix) {
  15872. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15873. }
  15874. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15875. // Parent
  15876. if (parsedTransformNode.parentId) {
  15877. transformNode._waitingParentId = parsedTransformNode.parentId;
  15878. }
  15879. return transformNode;
  15880. };
  15881. /**
  15882. * Disposes the TransformNode.
  15883. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15884. * Returns nothing.
  15885. */
  15886. TransformNode.prototype.dispose = function (doNotRecurse) {
  15887. // Animations
  15888. this.getScene().stopAnimation(this);
  15889. // Remove from scene
  15890. this.getScene().removeTransformNode(this);
  15891. if (!doNotRecurse) {
  15892. // Children
  15893. var objects = this.getDescendants(true);
  15894. for (var index = 0; index < objects.length; index++) {
  15895. objects[index].dispose();
  15896. }
  15897. }
  15898. else {
  15899. var childMeshes = this.getChildMeshes(true);
  15900. for (index = 0; index < childMeshes.length; index++) {
  15901. var child = childMeshes[index];
  15902. child.parent = null;
  15903. child.computeWorldMatrix(true);
  15904. }
  15905. }
  15906. this.onAfterWorldMatrixUpdateObservable.clear();
  15907. _super.prototype.dispose.call(this);
  15908. };
  15909. // Statics
  15910. TransformNode.BILLBOARDMODE_NONE = 0;
  15911. TransformNode.BILLBOARDMODE_X = 1;
  15912. TransformNode.BILLBOARDMODE_Y = 2;
  15913. TransformNode.BILLBOARDMODE_Z = 4;
  15914. TransformNode.BILLBOARDMODE_ALL = 7;
  15915. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15916. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15917. __decorate([
  15918. BABYLON.serializeAsVector3()
  15919. ], TransformNode.prototype, "_rotation", void 0);
  15920. __decorate([
  15921. BABYLON.serializeAsQuaternion()
  15922. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15923. __decorate([
  15924. BABYLON.serializeAsVector3()
  15925. ], TransformNode.prototype, "_scaling", void 0);
  15926. __decorate([
  15927. BABYLON.serialize()
  15928. ], TransformNode.prototype, "billboardMode", void 0);
  15929. __decorate([
  15930. BABYLON.serialize()
  15931. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15932. __decorate([
  15933. BABYLON.serialize()
  15934. ], TransformNode.prototype, "infiniteDistance", void 0);
  15935. __decorate([
  15936. BABYLON.serializeAsVector3()
  15937. ], TransformNode.prototype, "position", void 0);
  15938. return TransformNode;
  15939. }(BABYLON.Node));
  15940. BABYLON.TransformNode = TransformNode;
  15941. })(BABYLON || (BABYLON = {}));
  15942. //# sourceMappingURL=babylon.transformNode.js.map
  15943. var BABYLON;
  15944. (function (BABYLON) {
  15945. var AbstractMesh = /** @class */ (function (_super) {
  15946. __extends(AbstractMesh, _super);
  15947. // Constructor
  15948. function AbstractMesh(name, scene) {
  15949. if (scene === void 0) { scene = null; }
  15950. var _this = _super.call(this, name, scene, false) || this;
  15951. _this._facetNb = 0; // facet number
  15952. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15953. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15954. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15955. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15956. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15957. _this._subDiv = {
  15958. max: 1,
  15959. X: 1,
  15960. Y: 1,
  15961. Z: 1
  15962. };
  15963. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15964. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15965. // Events
  15966. /**
  15967. * An event triggered when this mesh collides with another one
  15968. * @type {BABYLON.Observable}
  15969. */
  15970. _this.onCollideObservable = new BABYLON.Observable();
  15971. /**
  15972. * An event triggered when the collision's position changes
  15973. * @type {BABYLON.Observable}
  15974. */
  15975. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15976. /**
  15977. * An event triggered when material is changed
  15978. * @type {BABYLON.Observable}
  15979. */
  15980. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15981. // Properties
  15982. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15983. /**
  15984. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15985. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15986. * or
  15987. * 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.
  15988. * for more info check WebGl documentations
  15989. */
  15990. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15991. /**
  15992. * 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:
  15993. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15994. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15995. * 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.
  15996. */
  15997. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15998. /**
  15999. * 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.
  16000. * The default value is -1 which means don't break the query and wait till the result.
  16001. */
  16002. _this.occlusionRetryCount = -1;
  16003. _this._occlusionInternalRetryCounter = 0;
  16004. _this._isOccluded = false;
  16005. _this._isOcclusionQueryInProgress = false;
  16006. _this._visibility = 1.0;
  16007. _this.alphaIndex = Number.MAX_VALUE;
  16008. _this.isVisible = true;
  16009. _this.isPickable = true;
  16010. _this.showBoundingBox = false;
  16011. _this.showSubMeshesBoundingBox = false;
  16012. _this.isBlocker = false;
  16013. _this.enablePointerMoveEvents = false;
  16014. _this.renderingGroupId = 0;
  16015. _this._receiveShadows = false;
  16016. _this.renderOutline = false;
  16017. _this.outlineColor = BABYLON.Color3.Red();
  16018. _this.outlineWidth = 0.02;
  16019. _this.renderOverlay = false;
  16020. _this.overlayColor = BABYLON.Color3.Red();
  16021. _this.overlayAlpha = 0.5;
  16022. _this._hasVertexAlpha = false;
  16023. _this._useVertexColors = true;
  16024. _this._computeBonesUsingShaders = true;
  16025. _this._numBoneInfluencers = 4;
  16026. _this._applyFog = true;
  16027. _this.useOctreeForRenderingSelection = true;
  16028. _this.useOctreeForPicking = true;
  16029. _this.useOctreeForCollisions = true;
  16030. _this._layerMask = 0x0FFFFFFF;
  16031. /**
  16032. * True if the mesh must be rendered in any case.
  16033. */
  16034. _this.alwaysSelectAsActiveMesh = false;
  16035. /**
  16036. * This scene's action manager
  16037. * @type {BABYLON.ActionManager}
  16038. */
  16039. _this.actionManager = null;
  16040. // Physics
  16041. _this.physicsImpostor = null;
  16042. // Collisions
  16043. _this._checkCollisions = false;
  16044. _this._collisionMask = -1;
  16045. _this._collisionGroup = -1;
  16046. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16047. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16048. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16049. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16050. // Edges
  16051. _this.edgesWidth = 1;
  16052. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16053. // Cache
  16054. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16055. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16056. _this._isDisposed = false;
  16057. _this._renderId = 0;
  16058. _this._intersectionsInProgress = new Array();
  16059. _this._unIndexed = false;
  16060. _this._lightSources = new Array();
  16061. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16062. if (collidedMesh === void 0) { collidedMesh = null; }
  16063. //TODO move this to the collision coordinator!
  16064. if (_this.getScene().workerCollisions)
  16065. newPosition.multiplyInPlace(_this._collider._radius);
  16066. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16067. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16068. _this.position.addInPlace(_this._diffPositionForCollisions);
  16069. }
  16070. if (collidedMesh) {
  16071. _this.onCollideObservable.notifyObservers(collidedMesh);
  16072. }
  16073. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16074. };
  16075. _this.getScene().addMesh(_this);
  16076. _this._resyncLightSources();
  16077. return _this;
  16078. }
  16079. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16080. get: function () {
  16081. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16087. get: function () {
  16088. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16089. },
  16090. enumerable: true,
  16091. configurable: true
  16092. });
  16093. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16094. get: function () {
  16095. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16101. get: function () {
  16102. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16108. get: function () {
  16109. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16110. },
  16111. enumerable: true,
  16112. configurable: true
  16113. });
  16114. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16115. /**
  16116. * Read-only : the number of facets in the mesh
  16117. */
  16118. get: function () {
  16119. return this._facetNb;
  16120. },
  16121. enumerable: true,
  16122. configurable: true
  16123. });
  16124. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16125. /**
  16126. * The number (integer) of subdivisions per axis in the partioning space
  16127. */
  16128. get: function () {
  16129. return this._partitioningSubdivisions;
  16130. },
  16131. set: function (nb) {
  16132. this._partitioningSubdivisions = nb;
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16138. /**
  16139. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16140. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16141. */
  16142. get: function () {
  16143. return this._partitioningBBoxRatio;
  16144. },
  16145. set: function (ratio) {
  16146. this._partitioningBBoxRatio = ratio;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16152. /**
  16153. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16154. * Works only for updatable meshes.
  16155. * Doesn't work with multi-materials.
  16156. */
  16157. get: function () {
  16158. return this._facetDepthSort;
  16159. },
  16160. set: function (sort) {
  16161. this._facetDepthSort = sort;
  16162. },
  16163. enumerable: true,
  16164. configurable: true
  16165. });
  16166. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16167. /**
  16168. * The location (Vector3) where the facet depth sort must be computed from.
  16169. * By default, the active camera position.
  16170. * Used only when facet depth sort is enabled.
  16171. */
  16172. get: function () {
  16173. return this._facetDepthSortFrom;
  16174. },
  16175. set: function (location) {
  16176. this._facetDepthSortFrom = location;
  16177. },
  16178. enumerable: true,
  16179. configurable: true
  16180. });
  16181. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16182. /**
  16183. * Read-only boolean : is the feature facetData enabled ?
  16184. */
  16185. get: function () {
  16186. return this._facetDataEnabled;
  16187. },
  16188. enumerable: true,
  16189. configurable: true
  16190. });
  16191. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16192. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16193. return false;
  16194. }
  16195. this._markSubMeshesAsMiscDirty();
  16196. return true;
  16197. };
  16198. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16199. set: function (callback) {
  16200. if (this._onCollideObserver) {
  16201. this.onCollideObservable.remove(this._onCollideObserver);
  16202. }
  16203. this._onCollideObserver = this.onCollideObservable.add(callback);
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16209. set: function (callback) {
  16210. if (this._onCollisionPositionChangeObserver) {
  16211. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16212. }
  16213. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16214. },
  16215. enumerable: true,
  16216. configurable: true
  16217. });
  16218. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16219. /**
  16220. * 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.
  16221. */
  16222. get: function () {
  16223. return this._isOccluded;
  16224. },
  16225. set: function (value) {
  16226. this._isOccluded = value;
  16227. },
  16228. enumerable: true,
  16229. configurable: true
  16230. });
  16231. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16232. /**
  16233. * Flag to check the progress status of the query
  16234. */
  16235. get: function () {
  16236. return this._isOcclusionQueryInProgress;
  16237. },
  16238. enumerable: true,
  16239. configurable: true
  16240. });
  16241. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16242. /**
  16243. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16244. */
  16245. get: function () {
  16246. return this._visibility;
  16247. },
  16248. /**
  16249. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16250. */
  16251. set: function (value) {
  16252. if (this._visibility === value) {
  16253. return;
  16254. }
  16255. this._visibility = value;
  16256. this._markSubMeshesAsMiscDirty();
  16257. },
  16258. enumerable: true,
  16259. configurable: true
  16260. });
  16261. Object.defineProperty(AbstractMesh.prototype, "material", {
  16262. get: function () {
  16263. return this._material;
  16264. },
  16265. set: function (value) {
  16266. if (this._material === value) {
  16267. return;
  16268. }
  16269. this._material = value;
  16270. if (this.onMaterialChangedObservable.hasObservers) {
  16271. this.onMaterialChangedObservable.notifyObservers(this);
  16272. }
  16273. if (!this.subMeshes) {
  16274. return;
  16275. }
  16276. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16277. var subMesh = _a[_i];
  16278. subMesh.setEffect(null);
  16279. }
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16285. get: function () {
  16286. return this._receiveShadows;
  16287. },
  16288. set: function (value) {
  16289. if (this._receiveShadows === value) {
  16290. return;
  16291. }
  16292. this._receiveShadows = value;
  16293. this._markSubMeshesAsLightDirty();
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16299. get: function () {
  16300. return this._hasVertexAlpha;
  16301. },
  16302. set: function (value) {
  16303. if (this._hasVertexAlpha === value) {
  16304. return;
  16305. }
  16306. this._hasVertexAlpha = value;
  16307. this._markSubMeshesAsAttributesDirty();
  16308. this._markSubMeshesAsMiscDirty();
  16309. },
  16310. enumerable: true,
  16311. configurable: true
  16312. });
  16313. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16314. get: function () {
  16315. return this._useVertexColors;
  16316. },
  16317. set: function (value) {
  16318. if (this._useVertexColors === value) {
  16319. return;
  16320. }
  16321. this._useVertexColors = value;
  16322. this._markSubMeshesAsAttributesDirty();
  16323. },
  16324. enumerable: true,
  16325. configurable: true
  16326. });
  16327. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16328. get: function () {
  16329. return this._computeBonesUsingShaders;
  16330. },
  16331. set: function (value) {
  16332. if (this._computeBonesUsingShaders === value) {
  16333. return;
  16334. }
  16335. this._computeBonesUsingShaders = value;
  16336. this._markSubMeshesAsAttributesDirty();
  16337. },
  16338. enumerable: true,
  16339. configurable: true
  16340. });
  16341. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16342. get: function () {
  16343. return this._numBoneInfluencers;
  16344. },
  16345. set: function (value) {
  16346. if (this._numBoneInfluencers === value) {
  16347. return;
  16348. }
  16349. this._numBoneInfluencers = value;
  16350. this._markSubMeshesAsAttributesDirty();
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16356. get: function () {
  16357. return this._applyFog;
  16358. },
  16359. set: function (value) {
  16360. if (this._applyFog === value) {
  16361. return;
  16362. }
  16363. this._applyFog = value;
  16364. this._markSubMeshesAsMiscDirty();
  16365. },
  16366. enumerable: true,
  16367. configurable: true
  16368. });
  16369. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16370. get: function () {
  16371. return this._layerMask;
  16372. },
  16373. set: function (value) {
  16374. if (value === this._layerMask) {
  16375. return;
  16376. }
  16377. this._layerMask = value;
  16378. this._resyncLightSources();
  16379. },
  16380. enumerable: true,
  16381. configurable: true
  16382. });
  16383. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16384. get: function () {
  16385. return this._collisionMask;
  16386. },
  16387. set: function (mask) {
  16388. this._collisionMask = !isNaN(mask) ? mask : -1;
  16389. },
  16390. enumerable: true,
  16391. configurable: true
  16392. });
  16393. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16394. get: function () {
  16395. return this._collisionGroup;
  16396. },
  16397. set: function (mask) {
  16398. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16399. },
  16400. enumerable: true,
  16401. configurable: true
  16402. });
  16403. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16404. get: function () {
  16405. return null;
  16406. },
  16407. enumerable: true,
  16408. configurable: true
  16409. });
  16410. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16411. get: function () {
  16412. return this._skeleton;
  16413. },
  16414. set: function (value) {
  16415. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16416. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16417. }
  16418. if (value && value.needInitialSkinMatrix) {
  16419. value._registerMeshWithPoseMatrix(this);
  16420. }
  16421. this._skeleton = value;
  16422. if (!this._skeleton) {
  16423. this._bonesTransformMatrices = null;
  16424. }
  16425. this._markSubMeshesAsAttributesDirty();
  16426. },
  16427. enumerable: true,
  16428. configurable: true
  16429. });
  16430. /**
  16431. * Boolean : true if the mesh has been disposed.
  16432. */
  16433. AbstractMesh.prototype.isDisposed = function () {
  16434. return this._isDisposed;
  16435. };
  16436. /**
  16437. * Returns the string "AbstractMesh"
  16438. */
  16439. AbstractMesh.prototype.getClassName = function () {
  16440. return "AbstractMesh";
  16441. };
  16442. /**
  16443. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16444. */
  16445. AbstractMesh.prototype.toString = function (fullDetails) {
  16446. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16447. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16448. if (this._skeleton) {
  16449. ret += ", skeleton: " + this._skeleton.name;
  16450. }
  16451. if (fullDetails) {
  16452. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16453. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16454. }
  16455. return ret;
  16456. };
  16457. AbstractMesh.prototype._rebuild = function () {
  16458. if (this._occlusionQuery) {
  16459. this._occlusionQuery = null;
  16460. }
  16461. if (this._edgesRenderer) {
  16462. this._edgesRenderer._rebuild();
  16463. }
  16464. if (!this.subMeshes) {
  16465. return;
  16466. }
  16467. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16468. var subMesh = _a[_i];
  16469. subMesh._rebuild();
  16470. }
  16471. };
  16472. AbstractMesh.prototype._resyncLightSources = function () {
  16473. this._lightSources.length = 0;
  16474. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16475. var light = _a[_i];
  16476. if (!light.isEnabled()) {
  16477. continue;
  16478. }
  16479. if (light.canAffectMesh(this)) {
  16480. this._lightSources.push(light);
  16481. }
  16482. }
  16483. this._markSubMeshesAsLightDirty();
  16484. };
  16485. AbstractMesh.prototype._resyncLighSource = function (light) {
  16486. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16487. var index = this._lightSources.indexOf(light);
  16488. if (index === -1) {
  16489. if (!isIn) {
  16490. return;
  16491. }
  16492. this._lightSources.push(light);
  16493. }
  16494. else {
  16495. if (isIn) {
  16496. return;
  16497. }
  16498. this._lightSources.splice(index, 1);
  16499. }
  16500. this._markSubMeshesAsLightDirty();
  16501. };
  16502. AbstractMesh.prototype._removeLightSource = function (light) {
  16503. var index = this._lightSources.indexOf(light);
  16504. if (index === -1) {
  16505. return;
  16506. }
  16507. this._lightSources.splice(index, 1);
  16508. this._markSubMeshesAsLightDirty();
  16509. };
  16510. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16511. if (!this.subMeshes) {
  16512. return;
  16513. }
  16514. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16515. var subMesh = _a[_i];
  16516. if (subMesh._materialDefines) {
  16517. func(subMesh._materialDefines);
  16518. }
  16519. }
  16520. };
  16521. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16522. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16523. };
  16524. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16525. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16526. };
  16527. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16528. if (!this.subMeshes) {
  16529. return;
  16530. }
  16531. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16532. var subMesh = _a[_i];
  16533. var material = subMesh.getMaterial();
  16534. if (material) {
  16535. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16536. }
  16537. }
  16538. };
  16539. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16540. /**
  16541. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16542. * Default : (1.0, 1.0, 1.0)
  16543. */
  16544. get: function () {
  16545. return this._scaling;
  16546. },
  16547. /**
  16548. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16549. * Default : (1.0, 1.0, 1.0)
  16550. */
  16551. set: function (newScaling) {
  16552. this._scaling = newScaling;
  16553. if (this.physicsImpostor) {
  16554. this.physicsImpostor.forceUpdate();
  16555. }
  16556. },
  16557. enumerable: true,
  16558. configurable: true
  16559. });
  16560. // Methods
  16561. /**
  16562. * Disables the mesh edger rendering mode.
  16563. * Returns the AbstractMesh.
  16564. */
  16565. AbstractMesh.prototype.disableEdgesRendering = function () {
  16566. if (this._edgesRenderer) {
  16567. this._edgesRenderer.dispose();
  16568. this._edgesRenderer = null;
  16569. }
  16570. return this;
  16571. };
  16572. /**
  16573. * Enables the edge rendering mode on the mesh.
  16574. * This mode makes the mesh edges visible.
  16575. * Returns the AbstractMesh.
  16576. */
  16577. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16578. if (epsilon === void 0) { epsilon = 0.95; }
  16579. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16580. this.disableEdgesRendering();
  16581. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16582. return this;
  16583. };
  16584. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16585. /**
  16586. * Returns true if the mesh is blocked. Used by the class Mesh.
  16587. * Returns the boolean `false` by default.
  16588. */
  16589. get: function () {
  16590. return false;
  16591. },
  16592. enumerable: true,
  16593. configurable: true
  16594. });
  16595. /**
  16596. * Returns the mesh itself by default, used by the class Mesh.
  16597. * Returned type : AbstractMesh
  16598. */
  16599. AbstractMesh.prototype.getLOD = function (camera) {
  16600. return this;
  16601. };
  16602. /**
  16603. * Returns 0 by default, used by the class Mesh.
  16604. * Returns an integer.
  16605. */
  16606. AbstractMesh.prototype.getTotalVertices = function () {
  16607. return 0;
  16608. };
  16609. /**
  16610. * Returns null by default, used by the class Mesh.
  16611. * Returned type : integer array
  16612. */
  16613. AbstractMesh.prototype.getIndices = function () {
  16614. return null;
  16615. };
  16616. /**
  16617. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16618. * Returned type : float array or Float32Array
  16619. */
  16620. AbstractMesh.prototype.getVerticesData = function (kind) {
  16621. return null;
  16622. };
  16623. /**
  16624. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16625. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16626. * The `data` are either a numeric array either a Float32Array.
  16627. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16628. * 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).
  16629. * Note that a new underlying VertexBuffer object is created each call.
  16630. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16631. *
  16632. * Possible `kind` values :
  16633. * - BABYLON.VertexBuffer.PositionKind
  16634. * - BABYLON.VertexBuffer.UVKind
  16635. * - BABYLON.VertexBuffer.UV2Kind
  16636. * - BABYLON.VertexBuffer.UV3Kind
  16637. * - BABYLON.VertexBuffer.UV4Kind
  16638. * - BABYLON.VertexBuffer.UV5Kind
  16639. * - BABYLON.VertexBuffer.UV6Kind
  16640. * - BABYLON.VertexBuffer.ColorKind
  16641. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16642. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16643. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16644. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16645. *
  16646. * Returns the Mesh.
  16647. */
  16648. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16649. return this;
  16650. };
  16651. /**
  16652. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16653. * If the mesh has no geometry, it is simply returned as it is.
  16654. * The `data` are either a numeric array either a Float32Array.
  16655. * No new underlying VertexBuffer object is created.
  16656. * 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.
  16657. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16658. *
  16659. * Possible `kind` values :
  16660. * - BABYLON.VertexBuffer.PositionKind
  16661. * - BABYLON.VertexBuffer.UVKind
  16662. * - BABYLON.VertexBuffer.UV2Kind
  16663. * - BABYLON.VertexBuffer.UV3Kind
  16664. * - BABYLON.VertexBuffer.UV4Kind
  16665. * - BABYLON.VertexBuffer.UV5Kind
  16666. * - BABYLON.VertexBuffer.UV6Kind
  16667. * - BABYLON.VertexBuffer.ColorKind
  16668. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16669. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16670. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16671. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16672. *
  16673. * Returns the Mesh.
  16674. */
  16675. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16676. return this;
  16677. };
  16678. /**
  16679. * Sets the mesh indices.
  16680. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16681. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16682. * This method creates a new index buffer each call.
  16683. * Returns the Mesh.
  16684. */
  16685. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16686. return this;
  16687. };
  16688. /** Returns false by default, used by the class Mesh.
  16689. * Returns a boolean
  16690. */
  16691. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16692. return false;
  16693. };
  16694. /**
  16695. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16696. * Returns a BoundingInfo
  16697. */
  16698. AbstractMesh.prototype.getBoundingInfo = function () {
  16699. if (this._masterMesh) {
  16700. return this._masterMesh.getBoundingInfo();
  16701. }
  16702. if (!this._boundingInfo) {
  16703. // this._boundingInfo is being created here
  16704. this._updateBoundingInfo();
  16705. }
  16706. // cannot be null.
  16707. return this._boundingInfo;
  16708. };
  16709. /**
  16710. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16711. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16712. */
  16713. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16714. if (includeDescendants === void 0) { includeDescendants = true; }
  16715. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16716. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16717. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16718. if (maxDimension === 0) {
  16719. return this;
  16720. }
  16721. var scale = 1 / maxDimension;
  16722. this.scaling.scaleInPlace(scale);
  16723. return this;
  16724. };
  16725. /**
  16726. * Sets a mesh new object BoundingInfo.
  16727. * Returns the AbstractMesh.
  16728. */
  16729. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16730. this._boundingInfo = boundingInfo;
  16731. return this;
  16732. };
  16733. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16734. get: function () {
  16735. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16736. },
  16737. enumerable: true,
  16738. configurable: true
  16739. });
  16740. AbstractMesh.prototype._preActivate = function () {
  16741. };
  16742. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16743. };
  16744. AbstractMesh.prototype._activate = function (renderId) {
  16745. this._renderId = renderId;
  16746. };
  16747. /**
  16748. * Returns the latest update of the World matrix
  16749. * Returns a Matrix.
  16750. */
  16751. AbstractMesh.prototype.getWorldMatrix = function () {
  16752. if (this._masterMesh) {
  16753. return this._masterMesh.getWorldMatrix();
  16754. }
  16755. return _super.prototype.getWorldMatrix.call(this);
  16756. };
  16757. /**
  16758. * Returns the latest update of the World matrix determinant.
  16759. */
  16760. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16761. if (this._masterMesh) {
  16762. return this._masterMesh._getWorldMatrixDeterminant();
  16763. }
  16764. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16765. };
  16766. // ================================== Point of View Movement =================================
  16767. /**
  16768. * Perform relative position change from the point of view of behind the front of the mesh.
  16769. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16770. * Supports definition of mesh facing forward or backward.
  16771. * @param {number} amountRight
  16772. * @param {number} amountUp
  16773. * @param {number} amountForward
  16774. *
  16775. * Returns the AbstractMesh.
  16776. */
  16777. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16778. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16779. return this;
  16780. };
  16781. /**
  16782. * Calculate relative position change from the point of view of behind the front of the mesh.
  16783. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16784. * Supports definition of mesh facing forward or backward.
  16785. * @param {number} amountRight
  16786. * @param {number} amountUp
  16787. * @param {number} amountForward
  16788. *
  16789. * Returns a new Vector3.
  16790. */
  16791. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16792. var rotMatrix = new BABYLON.Matrix();
  16793. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16794. rotQuaternion.toRotationMatrix(rotMatrix);
  16795. var translationDelta = BABYLON.Vector3.Zero();
  16796. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16797. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16798. return translationDelta;
  16799. };
  16800. // ================================== Point of View Rotation =================================
  16801. /**
  16802. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16803. * Supports definition of mesh facing forward or backward.
  16804. * @param {number} flipBack
  16805. * @param {number} twirlClockwise
  16806. * @param {number} tiltRight
  16807. *
  16808. * Returns the AbstractMesh.
  16809. */
  16810. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16811. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16812. return this;
  16813. };
  16814. /**
  16815. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16816. * Supports definition of mesh facing forward or backward.
  16817. * @param {number} flipBack
  16818. * @param {number} twirlClockwise
  16819. * @param {number} tiltRight
  16820. *
  16821. * Returns a new Vector3.
  16822. */
  16823. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16824. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16825. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16826. };
  16827. /**
  16828. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16829. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16830. */
  16831. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16832. if (includeDescendants === void 0) { includeDescendants = true; }
  16833. this.computeWorldMatrix(true);
  16834. var min;
  16835. var max;
  16836. var boundingInfo = this.getBoundingInfo();
  16837. if (!this.subMeshes) {
  16838. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16839. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16840. }
  16841. else {
  16842. min = boundingInfo.boundingBox.minimumWorld;
  16843. max = boundingInfo.boundingBox.maximumWorld;
  16844. }
  16845. if (includeDescendants) {
  16846. var descendants = this.getDescendants(false);
  16847. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16848. var descendant = descendants_1[_i];
  16849. var childMesh = descendant;
  16850. childMesh.computeWorldMatrix(true);
  16851. //make sure we have the needed params to get mix and max
  16852. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16853. continue;
  16854. }
  16855. var childBoundingInfo = childMesh.getBoundingInfo();
  16856. var boundingBox = childBoundingInfo.boundingBox;
  16857. var minBox = boundingBox.minimumWorld;
  16858. var maxBox = boundingBox.maximumWorld;
  16859. BABYLON.Tools.CheckExtends(minBox, min, max);
  16860. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16861. }
  16862. }
  16863. return {
  16864. min: min,
  16865. max: max
  16866. };
  16867. };
  16868. /**
  16869. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16870. * Returns the AbstractMesh.
  16871. */
  16872. AbstractMesh.prototype._updateBoundingInfo = function () {
  16873. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16874. this._boundingInfo.update(this.worldMatrixFromCache);
  16875. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16876. return this;
  16877. };
  16878. /**
  16879. * Update a mesh's children BoundingInfo objects only.
  16880. * Returns the AbstractMesh.
  16881. */
  16882. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16883. if (!this.subMeshes) {
  16884. return this;
  16885. }
  16886. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16887. var subMesh = this.subMeshes[subIndex];
  16888. if (!subMesh.IsGlobal) {
  16889. subMesh.updateBoundingInfo(matrix);
  16890. }
  16891. }
  16892. return this;
  16893. };
  16894. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16895. // Bounding info
  16896. this._updateBoundingInfo();
  16897. };
  16898. /**
  16899. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16900. * A mesh is in the frustum if its bounding box intersects the frustum.
  16901. * Boolean returned.
  16902. */
  16903. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16904. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16905. };
  16906. /**
  16907. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16908. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16909. * Boolean returned.
  16910. */
  16911. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16912. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16913. ;
  16914. };
  16915. /**
  16916. * True if the mesh intersects another mesh or a SolidParticle object.
  16917. * 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)
  16918. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16919. * Returns a boolean.
  16920. */
  16921. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16922. if (precise === void 0) { precise = false; }
  16923. if (!this._boundingInfo || !mesh._boundingInfo) {
  16924. return false;
  16925. }
  16926. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16927. return true;
  16928. }
  16929. if (includeDescendants) {
  16930. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16931. var child = _a[_i];
  16932. if (child.intersectsMesh(mesh, precise, true)) {
  16933. return true;
  16934. }
  16935. }
  16936. }
  16937. return false;
  16938. };
  16939. /**
  16940. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16941. * Returns a boolean.
  16942. */
  16943. AbstractMesh.prototype.intersectsPoint = function (point) {
  16944. if (!this._boundingInfo) {
  16945. return false;
  16946. }
  16947. return this._boundingInfo.intersectsPoint(point);
  16948. };
  16949. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16950. return this.physicsImpostor;
  16951. };
  16952. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16953. if (camera === void 0) { camera = null; }
  16954. if (!camera) {
  16955. camera = this.getScene().activeCamera;
  16956. }
  16957. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16958. };
  16959. /**
  16960. * Returns the distance from the mesh to the active camera.
  16961. * Returns a float.
  16962. */
  16963. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16964. if (camera === void 0) { camera = null; }
  16965. if (!camera) {
  16966. camera = this.getScene().activeCamera;
  16967. }
  16968. return this.absolutePosition.subtract(camera.position).length();
  16969. };
  16970. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16971. if (!this.physicsImpostor) {
  16972. return this;
  16973. }
  16974. this.physicsImpostor.applyImpulse(force, contactPoint);
  16975. return this;
  16976. };
  16977. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16978. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16979. return this;
  16980. }
  16981. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16982. mainPivot: pivot1,
  16983. connectedPivot: pivot2,
  16984. nativeParams: options
  16985. });
  16986. return this;
  16987. };
  16988. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16989. // Collisions
  16990. /**
  16991. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16992. * Default `false`.
  16993. */
  16994. get: function () {
  16995. return this._checkCollisions;
  16996. },
  16997. set: function (collisionEnabled) {
  16998. this._checkCollisions = collisionEnabled;
  16999. if (this.getScene().workerCollisions) {
  17000. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17001. }
  17002. },
  17003. enumerable: true,
  17004. configurable: true
  17005. });
  17006. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17007. /**
  17008. * Gets Collider object used to compute collisions (not physics)
  17009. */
  17010. get: function () {
  17011. return this._collider;
  17012. },
  17013. enumerable: true,
  17014. configurable: true
  17015. });
  17016. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17017. var globalPosition = this.getAbsolutePosition();
  17018. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17019. if (!this._collider) {
  17020. this._collider = new BABYLON.Collider();
  17021. }
  17022. this._collider._radius = this.ellipsoid;
  17023. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17024. return this;
  17025. };
  17026. // Submeshes octree
  17027. /**
  17028. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17029. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17030. * Returns an Octree of submeshes.
  17031. */
  17032. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17033. if (maxCapacity === void 0) { maxCapacity = 64; }
  17034. if (maxDepth === void 0) { maxDepth = 2; }
  17035. if (!this._submeshesOctree) {
  17036. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17037. }
  17038. this.computeWorldMatrix(true);
  17039. var boundingInfo = this.getBoundingInfo();
  17040. // Update octree
  17041. var bbox = boundingInfo.boundingBox;
  17042. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17043. return this._submeshesOctree;
  17044. };
  17045. // Collisions
  17046. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17047. this._generatePointsArray();
  17048. if (!this._positions) {
  17049. return this;
  17050. }
  17051. // Transformation
  17052. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17053. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17054. subMesh._lastColliderWorldVertices = [];
  17055. subMesh._trianglePlanes = [];
  17056. var start = subMesh.verticesStart;
  17057. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17058. for (var i = start; i < end; i++) {
  17059. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17060. }
  17061. }
  17062. // Collide
  17063. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17064. if (collider.collisionFound) {
  17065. collider.collidedMesh = this;
  17066. }
  17067. return this;
  17068. };
  17069. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17070. var subMeshes;
  17071. var len;
  17072. // Octrees
  17073. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17074. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17075. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17076. len = intersections.length;
  17077. subMeshes = intersections.data;
  17078. }
  17079. else {
  17080. subMeshes = this.subMeshes;
  17081. len = subMeshes.length;
  17082. }
  17083. for (var index = 0; index < len; index++) {
  17084. var subMesh = subMeshes[index];
  17085. // Bounding test
  17086. if (len > 1 && !subMesh._checkCollision(collider))
  17087. continue;
  17088. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17089. }
  17090. return this;
  17091. };
  17092. AbstractMesh.prototype._checkCollision = function (collider) {
  17093. // Bounding box test
  17094. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17095. return this;
  17096. // Transformation matrix
  17097. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17098. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17099. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17100. return this;
  17101. };
  17102. // Picking
  17103. AbstractMesh.prototype._generatePointsArray = function () {
  17104. return false;
  17105. };
  17106. /**
  17107. * Checks if the passed Ray intersects with the mesh.
  17108. * Returns an object PickingInfo.
  17109. */
  17110. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17111. var pickingInfo = new BABYLON.PickingInfo();
  17112. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17113. return pickingInfo;
  17114. }
  17115. if (!this._generatePointsArray()) {
  17116. return pickingInfo;
  17117. }
  17118. var intersectInfo = null;
  17119. // Octrees
  17120. var subMeshes;
  17121. var len;
  17122. if (this._submeshesOctree && this.useOctreeForPicking) {
  17123. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17124. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17125. len = intersections.length;
  17126. subMeshes = intersections.data;
  17127. }
  17128. else {
  17129. subMeshes = this.subMeshes;
  17130. len = subMeshes.length;
  17131. }
  17132. for (var index = 0; index < len; index++) {
  17133. var subMesh = subMeshes[index];
  17134. // Bounding test
  17135. if (len > 1 && !subMesh.canIntersects(ray))
  17136. continue;
  17137. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17138. if (currentIntersectInfo) {
  17139. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17140. intersectInfo = currentIntersectInfo;
  17141. intersectInfo.subMeshId = index;
  17142. if (fastCheck) {
  17143. break;
  17144. }
  17145. }
  17146. }
  17147. }
  17148. if (intersectInfo) {
  17149. // Get picked point
  17150. var world = this.getWorldMatrix();
  17151. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17152. var direction = ray.direction.clone();
  17153. direction = direction.scale(intersectInfo.distance);
  17154. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17155. var pickedPoint = worldOrigin.add(worldDirection);
  17156. // Return result
  17157. pickingInfo.hit = true;
  17158. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17159. pickingInfo.pickedPoint = pickedPoint;
  17160. pickingInfo.pickedMesh = this;
  17161. pickingInfo.bu = intersectInfo.bu || 0;
  17162. pickingInfo.bv = intersectInfo.bv || 0;
  17163. pickingInfo.faceId = intersectInfo.faceId;
  17164. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17165. return pickingInfo;
  17166. }
  17167. return pickingInfo;
  17168. };
  17169. /**
  17170. * Clones the mesh, used by the class Mesh.
  17171. * Just returns `null` for an AbstractMesh.
  17172. */
  17173. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17174. return null;
  17175. };
  17176. /**
  17177. * Disposes all the mesh submeshes.
  17178. * Returns the AbstractMesh.
  17179. */
  17180. AbstractMesh.prototype.releaseSubMeshes = function () {
  17181. if (this.subMeshes) {
  17182. while (this.subMeshes.length) {
  17183. this.subMeshes[0].dispose();
  17184. }
  17185. }
  17186. else {
  17187. this.subMeshes = new Array();
  17188. }
  17189. return this;
  17190. };
  17191. /**
  17192. * Disposes the AbstractMesh.
  17193. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17194. * Returns nothing.
  17195. */
  17196. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17197. var _this = this;
  17198. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17199. var index;
  17200. // Action manager
  17201. if (this.actionManager !== undefined && this.actionManager !== null) {
  17202. this.actionManager.dispose();
  17203. this.actionManager = null;
  17204. }
  17205. // Skeleton
  17206. this.skeleton = null;
  17207. // Physics
  17208. if (this.physicsImpostor) {
  17209. this.physicsImpostor.dispose();
  17210. }
  17211. // Intersections in progress
  17212. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17213. var other = this._intersectionsInProgress[index];
  17214. var pos = other._intersectionsInProgress.indexOf(this);
  17215. other._intersectionsInProgress.splice(pos, 1);
  17216. }
  17217. this._intersectionsInProgress = [];
  17218. // Lights
  17219. var lights = this.getScene().lights;
  17220. lights.forEach(function (light) {
  17221. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17222. if (meshIndex !== -1) {
  17223. light.includedOnlyMeshes.splice(meshIndex, 1);
  17224. }
  17225. meshIndex = light.excludedMeshes.indexOf(_this);
  17226. if (meshIndex !== -1) {
  17227. light.excludedMeshes.splice(meshIndex, 1);
  17228. }
  17229. // Shadow generators
  17230. var generator = light.getShadowGenerator();
  17231. if (generator) {
  17232. var shadowMap = generator.getShadowMap();
  17233. if (shadowMap && shadowMap.renderList) {
  17234. meshIndex = shadowMap.renderList.indexOf(_this);
  17235. if (meshIndex !== -1) {
  17236. shadowMap.renderList.splice(meshIndex, 1);
  17237. }
  17238. }
  17239. }
  17240. });
  17241. // Edges
  17242. if (this._edgesRenderer) {
  17243. this._edgesRenderer.dispose();
  17244. this._edgesRenderer = null;
  17245. }
  17246. // SubMeshes
  17247. if (this.getClassName() !== "InstancedMesh") {
  17248. this.releaseSubMeshes();
  17249. }
  17250. // Octree
  17251. var sceneOctree = this.getScene().selectionOctree;
  17252. if (sceneOctree !== undefined && sceneOctree !== null) {
  17253. var index = sceneOctree.dynamicContent.indexOf(this);
  17254. if (index !== -1) {
  17255. sceneOctree.dynamicContent.splice(index, 1);
  17256. }
  17257. }
  17258. // Query
  17259. var engine = this.getScene().getEngine();
  17260. if (this._occlusionQuery) {
  17261. this._isOcclusionQueryInProgress = false;
  17262. engine.deleteQuery(this._occlusionQuery);
  17263. this._occlusionQuery = null;
  17264. }
  17265. // Engine
  17266. engine.wipeCaches();
  17267. // Remove from scene
  17268. this.getScene().removeMesh(this);
  17269. if (disposeMaterialAndTextures) {
  17270. if (this.material) {
  17271. this.material.dispose(false, true);
  17272. }
  17273. }
  17274. if (!doNotRecurse) {
  17275. // Particles
  17276. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17277. if (this.getScene().particleSystems[index].emitter === this) {
  17278. this.getScene().particleSystems[index].dispose();
  17279. index--;
  17280. }
  17281. }
  17282. }
  17283. // facet data
  17284. if (this._facetDataEnabled) {
  17285. this.disableFacetData();
  17286. }
  17287. this.onAfterWorldMatrixUpdateObservable.clear();
  17288. this.onCollideObservable.clear();
  17289. this.onCollisionPositionChangeObservable.clear();
  17290. this._isDisposed = true;
  17291. _super.prototype.dispose.call(this, doNotRecurse);
  17292. };
  17293. /**
  17294. * Adds the passed mesh as a child to the current mesh.
  17295. * Returns the AbstractMesh.
  17296. */
  17297. AbstractMesh.prototype.addChild = function (mesh) {
  17298. mesh.setParent(this);
  17299. return this;
  17300. };
  17301. /**
  17302. * Removes the passed mesh from the current mesh children list.
  17303. * Returns the AbstractMesh.
  17304. */
  17305. AbstractMesh.prototype.removeChild = function (mesh) {
  17306. mesh.setParent(null);
  17307. return this;
  17308. };
  17309. // Facet data
  17310. /**
  17311. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17312. * Returns the AbstractMesh.
  17313. */
  17314. AbstractMesh.prototype._initFacetData = function () {
  17315. if (!this._facetNormals) {
  17316. this._facetNormals = new Array();
  17317. }
  17318. if (!this._facetPositions) {
  17319. this._facetPositions = new Array();
  17320. }
  17321. if (!this._facetPartitioning) {
  17322. this._facetPartitioning = new Array();
  17323. }
  17324. this._facetNb = (this.getIndices().length / 3) | 0;
  17325. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17326. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17327. for (var f = 0; f < this._facetNb; f++) {
  17328. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17329. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17330. }
  17331. this._facetDataEnabled = true;
  17332. return this;
  17333. };
  17334. /**
  17335. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17336. * This method can be called within the render loop.
  17337. * 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.
  17338. * Returns the AbstractMesh.
  17339. */
  17340. AbstractMesh.prototype.updateFacetData = function () {
  17341. if (!this._facetDataEnabled) {
  17342. this._initFacetData();
  17343. }
  17344. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17345. var indices = this.getIndices();
  17346. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17347. var bInfo = this.getBoundingInfo();
  17348. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17349. // init arrays, matrix and sort function on first call
  17350. this._facetDepthSortEnabled = true;
  17351. if (indices instanceof Uint16Array) {
  17352. this._depthSortedIndices = new Uint16Array(indices);
  17353. }
  17354. else if (indices instanceof Uint32Array) {
  17355. this._depthSortedIndices = new Uint32Array(indices);
  17356. }
  17357. else {
  17358. var needs32bits = false;
  17359. for (var i = 0; i < indices.length; i++) {
  17360. if (indices[i] > 65535) {
  17361. needs32bits = true;
  17362. break;
  17363. }
  17364. }
  17365. if (needs32bits) {
  17366. this._depthSortedIndices = new Uint32Array(indices);
  17367. }
  17368. else {
  17369. this._depthSortedIndices = new Uint16Array(indices);
  17370. }
  17371. }
  17372. this._facetDepthSortFunction = function (f1, f2) {
  17373. return (f2.sqDistance - f1.sqDistance);
  17374. };
  17375. if (!this._facetDepthSortFrom) {
  17376. var camera = this.getScene().activeCamera;
  17377. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17378. }
  17379. this._depthSortedFacets = [];
  17380. for (var f = 0; f < this._facetNb; f++) {
  17381. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17382. this._depthSortedFacets.push(depthSortedFacet);
  17383. }
  17384. this._invertedMatrix = BABYLON.Matrix.Identity();
  17385. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17386. }
  17387. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17388. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17389. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17390. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17391. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17392. this._subDiv.max = this._partitioningSubdivisions;
  17393. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17394. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17395. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17396. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17397. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17398. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17399. // set the parameters for ComputeNormals()
  17400. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17401. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17402. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17403. this._facetParameters.bInfo = bInfo;
  17404. this._facetParameters.bbSize = this._bbSize;
  17405. this._facetParameters.subDiv = this._subDiv;
  17406. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17407. this._facetParameters.depthSort = this._facetDepthSort;
  17408. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17409. this.computeWorldMatrix(true);
  17410. this._worldMatrix.invertToRef(this._invertedMatrix);
  17411. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17412. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17413. }
  17414. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17415. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17416. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17417. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17418. var l = (this._depthSortedIndices.length / 3) | 0;
  17419. for (var f = 0; f < l; f++) {
  17420. var sind = this._depthSortedFacets[f].ind;
  17421. this._depthSortedIndices[f * 3] = indices[sind];
  17422. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17423. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17424. }
  17425. this.updateIndices(this._depthSortedIndices);
  17426. }
  17427. return this;
  17428. };
  17429. /**
  17430. * Returns the facetLocalNormals array.
  17431. * The normals are expressed in the mesh local space.
  17432. */
  17433. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17434. if (!this._facetNormals) {
  17435. this.updateFacetData();
  17436. }
  17437. return this._facetNormals;
  17438. };
  17439. /**
  17440. * Returns the facetLocalPositions array.
  17441. * The facet positions are expressed in the mesh local space.
  17442. */
  17443. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17444. if (!this._facetPositions) {
  17445. this.updateFacetData();
  17446. }
  17447. return this._facetPositions;
  17448. };
  17449. /**
  17450. * Returns the facetLocalPartioning array.
  17451. */
  17452. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17453. if (!this._facetPartitioning) {
  17454. this.updateFacetData();
  17455. }
  17456. return this._facetPartitioning;
  17457. };
  17458. /**
  17459. * Returns the i-th facet position in the world system.
  17460. * This method allocates a new Vector3 per call.
  17461. */
  17462. AbstractMesh.prototype.getFacetPosition = function (i) {
  17463. var pos = BABYLON.Vector3.Zero();
  17464. this.getFacetPositionToRef(i, pos);
  17465. return pos;
  17466. };
  17467. /**
  17468. * Sets the reference Vector3 with the i-th facet position in the world system.
  17469. * Returns the AbstractMesh.
  17470. */
  17471. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17472. var localPos = (this.getFacetLocalPositions())[i];
  17473. var world = this.getWorldMatrix();
  17474. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17475. return this;
  17476. };
  17477. /**
  17478. * Returns the i-th facet normal in the world system.
  17479. * This method allocates a new Vector3 per call.
  17480. */
  17481. AbstractMesh.prototype.getFacetNormal = function (i) {
  17482. var norm = BABYLON.Vector3.Zero();
  17483. this.getFacetNormalToRef(i, norm);
  17484. return norm;
  17485. };
  17486. /**
  17487. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17488. * Returns the AbstractMesh.
  17489. */
  17490. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17491. var localNorm = (this.getFacetLocalNormals())[i];
  17492. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17493. return this;
  17494. };
  17495. /**
  17496. * 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).
  17497. */
  17498. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17499. var bInfo = this.getBoundingInfo();
  17500. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17501. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17502. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17503. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17504. return null;
  17505. }
  17506. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17507. };
  17508. /**
  17509. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17510. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17511. * 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.
  17512. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17513. * 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.
  17514. */
  17515. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17516. if (checkFace === void 0) { checkFace = false; }
  17517. if (facing === void 0) { facing = true; }
  17518. var world = this.getWorldMatrix();
  17519. var invMat = BABYLON.Tmp.Matrix[5];
  17520. world.invertToRef(invMat);
  17521. var invVect = BABYLON.Tmp.Vector3[8];
  17522. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17523. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17524. if (projected) {
  17525. // tranform the local computed projected vector to world coordinates
  17526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17527. }
  17528. return closest;
  17529. };
  17530. /**
  17531. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17532. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17533. * 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.
  17534. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17535. * 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.
  17536. */
  17537. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17538. if (checkFace === void 0) { checkFace = false; }
  17539. if (facing === void 0) { facing = true; }
  17540. var closest = null;
  17541. var tmpx = 0.0;
  17542. var tmpy = 0.0;
  17543. var tmpz = 0.0;
  17544. var d = 0.0; // tmp dot facet normal * facet position
  17545. var t0 = 0.0;
  17546. var projx = 0.0;
  17547. var projy = 0.0;
  17548. var projz = 0.0;
  17549. // Get all the facets in the same partitioning block than (x, y, z)
  17550. var facetPositions = this.getFacetLocalPositions();
  17551. var facetNormals = this.getFacetLocalNormals();
  17552. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17553. if (!facetsInBlock) {
  17554. return null;
  17555. }
  17556. // Get the closest facet to (x, y, z)
  17557. var shortest = Number.MAX_VALUE; // init distance vars
  17558. var tmpDistance = shortest;
  17559. var fib; // current facet in the block
  17560. var norm; // current facet normal
  17561. var p0; // current facet barycenter position
  17562. // loop on all the facets in the current partitioning block
  17563. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17564. fib = facetsInBlock[idx];
  17565. norm = facetNormals[fib];
  17566. p0 = facetPositions[fib];
  17567. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17568. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17569. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17570. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17571. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17572. projx = x + norm.x * t0;
  17573. projy = y + norm.y * t0;
  17574. projz = z + norm.z * t0;
  17575. tmpx = projx - x;
  17576. tmpy = projy - y;
  17577. tmpz = projz - z;
  17578. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17579. if (tmpDistance < shortest) {
  17580. shortest = tmpDistance;
  17581. closest = fib;
  17582. if (projected) {
  17583. projected.x = projx;
  17584. projected.y = projy;
  17585. projected.z = projz;
  17586. }
  17587. }
  17588. }
  17589. }
  17590. return closest;
  17591. };
  17592. /**
  17593. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17594. */
  17595. AbstractMesh.prototype.getFacetDataParameters = function () {
  17596. return this._facetParameters;
  17597. };
  17598. /**
  17599. * Disables the feature FacetData and frees the related memory.
  17600. * Returns the AbstractMesh.
  17601. */
  17602. AbstractMesh.prototype.disableFacetData = function () {
  17603. if (this._facetDataEnabled) {
  17604. this._facetDataEnabled = false;
  17605. this._facetPositions = new Array();
  17606. this._facetNormals = new Array();
  17607. this._facetPartitioning = new Array();
  17608. this._facetParameters = null;
  17609. this._depthSortedIndices = new Uint32Array(0);
  17610. }
  17611. return this;
  17612. };
  17613. /**
  17614. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17615. * Returns the mesh.
  17616. */
  17617. AbstractMesh.prototype.updateIndices = function (indices) {
  17618. return this;
  17619. };
  17620. /**
  17621. * The mesh Geometry. Actually used by the Mesh object.
  17622. * Returns a blank geometry object.
  17623. */
  17624. /**
  17625. * Creates new normals data for the mesh.
  17626. * @param updatable.
  17627. */
  17628. AbstractMesh.prototype.createNormals = function (updatable) {
  17629. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17630. var indices = this.getIndices();
  17631. var normals;
  17632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17633. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17634. }
  17635. else {
  17636. normals = [];
  17637. }
  17638. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17639. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17640. };
  17641. /**
  17642. * Align the mesh with a normal.
  17643. * Returns the mesh.
  17644. */
  17645. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17646. if (!upDirection) {
  17647. upDirection = BABYLON.Axis.Y;
  17648. }
  17649. var axisX = BABYLON.Tmp.Vector3[0];
  17650. var axisZ = BABYLON.Tmp.Vector3[1];
  17651. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17652. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17653. if (this.rotationQuaternion) {
  17654. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17655. }
  17656. else {
  17657. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17658. }
  17659. return this;
  17660. };
  17661. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17662. var engine = this.getEngine();
  17663. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17664. this._isOccluded = false;
  17665. return;
  17666. }
  17667. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17668. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17669. if (isOcclusionQueryAvailable) {
  17670. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17671. this._isOcclusionQueryInProgress = false;
  17672. this._occlusionInternalRetryCounter = 0;
  17673. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17674. }
  17675. else {
  17676. this._occlusionInternalRetryCounter++;
  17677. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17678. this._isOcclusionQueryInProgress = false;
  17679. this._occlusionInternalRetryCounter = 0;
  17680. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17681. // if strict continue the last state of the object.
  17682. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17683. }
  17684. else {
  17685. return;
  17686. }
  17687. }
  17688. }
  17689. var scene = this.getScene();
  17690. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17691. if (!this._occlusionQuery) {
  17692. this._occlusionQuery = engine.createQuery();
  17693. }
  17694. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17695. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17696. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17697. this._isOcclusionQueryInProgress = true;
  17698. };
  17699. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17700. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17701. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17702. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17703. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17704. return AbstractMesh;
  17705. }(BABYLON.TransformNode));
  17706. BABYLON.AbstractMesh = AbstractMesh;
  17707. })(BABYLON || (BABYLON = {}));
  17708. //# sourceMappingURL=babylon.abstractMesh.js.map
  17709. var BABYLON;
  17710. (function (BABYLON) {
  17711. /**
  17712. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  17713. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  17714. * 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.
  17715. */
  17716. var Light = /** @class */ (function (_super) {
  17717. __extends(Light, _super);
  17718. /**
  17719. * Creates a Light object in the scene.
  17720. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17721. * @param name The firendly name of the light
  17722. * @param scene The scene the light belongs too
  17723. */
  17724. function Light(name, scene) {
  17725. var _this = _super.call(this, name, scene) || this;
  17726. /**
  17727. * Diffuse gives the basic color to an object.
  17728. */
  17729. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17730. /**
  17731. * Specular produces a highlight color on an object.
  17732. * Note: This is note affecting PBR materials.
  17733. */
  17734. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17735. /**
  17736. * Strength of the light.
  17737. * Note: By default it is define in the framework own unit.
  17738. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  17739. */
  17740. _this.intensity = 1.0;
  17741. /**
  17742. * Defines how far from the source the light is impacting in scene units.
  17743. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  17744. */
  17745. _this.range = Number.MAX_VALUE;
  17746. /**
  17747. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17748. * of light.
  17749. */
  17750. _this._photometricScale = 1.0;
  17751. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17752. _this._radius = 0.00001;
  17753. /**
  17754. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  17755. * exceeding the number allowed of the materials.
  17756. */
  17757. _this.renderPriority = 0;
  17758. /**
  17759. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17760. * the current shadow generator.
  17761. */
  17762. _this.shadowEnabled = true;
  17763. _this._excludeWithLayerMask = 0;
  17764. _this._includeOnlyWithLayerMask = 0;
  17765. _this._lightmapMode = 0;
  17766. /**
  17767. * @ignore Internal use only.
  17768. */
  17769. _this._excludedMeshesIds = new Array();
  17770. /**
  17771. * @ignore Internal use only.
  17772. */
  17773. _this._includedOnlyMeshesIds = new Array();
  17774. _this.getScene().addLight(_this);
  17775. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17776. _this._buildUniformLayout();
  17777. _this.includedOnlyMeshes = new Array();
  17778. _this.excludedMeshes = new Array();
  17779. _this._resyncMeshes();
  17780. return _this;
  17781. }
  17782. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17783. /**
  17784. * If every light affecting the material is in this lightmapMode,
  17785. * material.lightmapTexture adds or multiplies
  17786. * (depends on material.useLightmapAsShadowmap)
  17787. * after every other light calculations.
  17788. */
  17789. get: function () {
  17790. return Light._LIGHTMAP_DEFAULT;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17796. /**
  17797. * material.lightmapTexture as only diffuse lighting from this light
  17798. * adds only specular lighting from this light
  17799. * adds dynamic shadows
  17800. */
  17801. get: function () {
  17802. return Light._LIGHTMAP_SPECULAR;
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17808. /**
  17809. * material.lightmapTexture as only lighting
  17810. * no light calculation from this light
  17811. * only adds dynamic shadows from this light
  17812. */
  17813. get: function () {
  17814. return Light._LIGHTMAP_SHADOWSONLY;
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17820. /**
  17821. * Each light type uses the default quantity according to its type:
  17822. * point/spot lights use luminous intensity
  17823. * directional lights use illuminance
  17824. */
  17825. get: function () {
  17826. return Light._INTENSITYMODE_AUTOMATIC;
  17827. },
  17828. enumerable: true,
  17829. configurable: true
  17830. });
  17831. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17832. /**
  17833. * lumen (lm)
  17834. */
  17835. get: function () {
  17836. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17842. /**
  17843. * candela (lm/sr)
  17844. */
  17845. get: function () {
  17846. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17847. },
  17848. enumerable: true,
  17849. configurable: true
  17850. });
  17851. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17852. /**
  17853. * lux (lm/m^2)
  17854. */
  17855. get: function () {
  17856. return Light._INTENSITYMODE_ILLUMINANCE;
  17857. },
  17858. enumerable: true,
  17859. configurable: true
  17860. });
  17861. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17862. /**
  17863. * nit (cd/m^2)
  17864. */
  17865. get: function () {
  17866. return Light._INTENSITYMODE_LUMINANCE;
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17872. /**
  17873. * Light type const id of the point light.
  17874. */
  17875. get: function () {
  17876. return Light._LIGHTTYPEID_POINTLIGHT;
  17877. },
  17878. enumerable: true,
  17879. configurable: true
  17880. });
  17881. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17882. /**
  17883. * Light type const id of the directional light.
  17884. */
  17885. get: function () {
  17886. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17892. /**
  17893. * Light type const id of the spot light.
  17894. */
  17895. get: function () {
  17896. return Light._LIGHTTYPEID_SPOTLIGHT;
  17897. },
  17898. enumerable: true,
  17899. configurable: true
  17900. });
  17901. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17902. /**
  17903. * Light type const id of the hemispheric light.
  17904. */
  17905. get: function () {
  17906. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. Object.defineProperty(Light.prototype, "intensityMode", {
  17912. /**
  17913. * Gets the photometric scale used to interpret the intensity.
  17914. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17915. */
  17916. get: function () {
  17917. return this._intensityMode;
  17918. },
  17919. /**
  17920. * Sets the photometric scale used to interpret the intensity.
  17921. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17922. */
  17923. set: function (value) {
  17924. this._intensityMode = value;
  17925. this._computePhotometricScale();
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. ;
  17931. ;
  17932. Object.defineProperty(Light.prototype, "radius", {
  17933. /**
  17934. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17935. */
  17936. get: function () {
  17937. return this._radius;
  17938. },
  17939. /**
  17940. * sets the light radius used by PBR Materials to simulate soft area lights.
  17941. */
  17942. set: function (value) {
  17943. this._radius = value;
  17944. this._computePhotometricScale();
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. ;
  17950. ;
  17951. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17952. /**
  17953. * Gets the only meshes impacted by this light.
  17954. */
  17955. get: function () {
  17956. return this._includedOnlyMeshes;
  17957. },
  17958. /**
  17959. * Sets the only meshes impacted by this light.
  17960. */
  17961. set: function (value) {
  17962. this._includedOnlyMeshes = value;
  17963. this._hookArrayForIncludedOnly(value);
  17964. },
  17965. enumerable: true,
  17966. configurable: true
  17967. });
  17968. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17969. /**
  17970. * Gets the meshes not impacted by this light.
  17971. */
  17972. get: function () {
  17973. return this._excludedMeshes;
  17974. },
  17975. /**
  17976. * Sets the meshes not impacted by this light.
  17977. */
  17978. set: function (value) {
  17979. this._excludedMeshes = value;
  17980. this._hookArrayForExcluded(value);
  17981. },
  17982. enumerable: true,
  17983. configurable: true
  17984. });
  17985. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17986. /**
  17987. * Gets the layer id use to find what meshes are not impacted by the light.
  17988. * Inactive if 0
  17989. */
  17990. get: function () {
  17991. return this._excludeWithLayerMask;
  17992. },
  17993. /**
  17994. * Sets the layer id use to find what meshes are not impacted by the light.
  17995. * Inactive if 0
  17996. */
  17997. set: function (value) {
  17998. this._excludeWithLayerMask = value;
  17999. this._resyncMeshes();
  18000. },
  18001. enumerable: true,
  18002. configurable: true
  18003. });
  18004. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18005. /**
  18006. * Gets the layer id use to find what meshes are impacted by the light.
  18007. * Inactive if 0
  18008. */
  18009. get: function () {
  18010. return this._includeOnlyWithLayerMask;
  18011. },
  18012. /**
  18013. * Sets the layer id use to find what meshes are impacted by the light.
  18014. * Inactive if 0
  18015. */
  18016. set: function (value) {
  18017. this._includeOnlyWithLayerMask = value;
  18018. this._resyncMeshes();
  18019. },
  18020. enumerable: true,
  18021. configurable: true
  18022. });
  18023. Object.defineProperty(Light.prototype, "lightmapMode", {
  18024. /**
  18025. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18026. */
  18027. get: function () {
  18028. return this._lightmapMode;
  18029. },
  18030. /**
  18031. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18032. */
  18033. set: function (value) {
  18034. if (this._lightmapMode === value) {
  18035. return;
  18036. }
  18037. this._lightmapMode = value;
  18038. this._markMeshesAsLightDirty();
  18039. },
  18040. enumerable: true,
  18041. configurable: true
  18042. });
  18043. /**
  18044. * Returns the string "Light".
  18045. * @returns the class name
  18046. */
  18047. Light.prototype.getClassName = function () {
  18048. return "Light";
  18049. };
  18050. /**
  18051. * Converts the light information to a readable string for debug purpose.
  18052. * @param fullDetails Supports for multiple levels of logging within scene loading
  18053. * @returns the human readable light info
  18054. */
  18055. Light.prototype.toString = function (fullDetails) {
  18056. var ret = "Name: " + this.name;
  18057. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18058. if (this.animations) {
  18059. for (var i = 0; i < this.animations.length; i++) {
  18060. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18061. }
  18062. }
  18063. if (fullDetails) {
  18064. }
  18065. return ret;
  18066. };
  18067. /**
  18068. * Set the enabled state of this node.
  18069. * @param value - the new enabled state
  18070. * @see isEnabled
  18071. */
  18072. Light.prototype.setEnabled = function (value) {
  18073. _super.prototype.setEnabled.call(this, value);
  18074. this._resyncMeshes();
  18075. };
  18076. /**
  18077. * Returns the Light associated shadow generator if any.
  18078. * @return the associated shadow generator.
  18079. */
  18080. Light.prototype.getShadowGenerator = function () {
  18081. return this._shadowGenerator;
  18082. };
  18083. /**
  18084. * Returns a Vector3, the absolute light position in the World.
  18085. * @returns the world space position of the light
  18086. */
  18087. Light.prototype.getAbsolutePosition = function () {
  18088. return BABYLON.Vector3.Zero();
  18089. };
  18090. /**
  18091. * Specifies if the light will affect the passed mesh.
  18092. * @param mesh The mesh to test against the light
  18093. * @return true the mesh is affected otherwise, false.
  18094. */
  18095. Light.prototype.canAffectMesh = function (mesh) {
  18096. if (!mesh) {
  18097. return true;
  18098. }
  18099. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18100. return false;
  18101. }
  18102. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18103. return false;
  18104. }
  18105. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18106. return false;
  18107. }
  18108. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18109. return false;
  18110. }
  18111. return true;
  18112. };
  18113. /**
  18114. * Computes and Returns the light World matrix.
  18115. * @returns the world matrix
  18116. */
  18117. Light.prototype.getWorldMatrix = function () {
  18118. this._currentRenderId = this.getScene().getRenderId();
  18119. var worldMatrix = this._getWorldMatrix();
  18120. if (this.parent && this.parent.getWorldMatrix) {
  18121. if (!this._parentedWorldMatrix) {
  18122. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18123. }
  18124. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18125. this._markSyncedWithParent();
  18126. return this._parentedWorldMatrix;
  18127. }
  18128. return worldMatrix;
  18129. };
  18130. /**
  18131. * Sort function to order lights for rendering.
  18132. * @param a First Light object to compare to second.
  18133. * @param b Second Light object to compare first.
  18134. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18135. */
  18136. Light.CompareLightsPriority = function (a, b) {
  18137. //shadow-casting lights have priority over non-shadow-casting lights
  18138. //the renderPrioirty is a secondary sort criterion
  18139. if (a.shadowEnabled !== b.shadowEnabled) {
  18140. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18141. }
  18142. return b.renderPriority - a.renderPriority;
  18143. };
  18144. /**
  18145. * Disposes the light.
  18146. */
  18147. Light.prototype.dispose = function () {
  18148. if (this._shadowGenerator) {
  18149. this._shadowGenerator.dispose();
  18150. this._shadowGenerator = null;
  18151. }
  18152. // Animations
  18153. this.getScene().stopAnimation(this);
  18154. // Remove from meshes
  18155. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18156. var mesh = _a[_i];
  18157. mesh._removeLightSource(this);
  18158. }
  18159. this._uniformBuffer.dispose();
  18160. // Remove from scene
  18161. this.getScene().removeLight(this);
  18162. _super.prototype.dispose.call(this);
  18163. };
  18164. /**
  18165. * Returns the light type ID (integer).
  18166. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18167. */
  18168. Light.prototype.getTypeID = function () {
  18169. return 0;
  18170. };
  18171. /**
  18172. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18173. * @returns the scaled intensity in intensity mode unit
  18174. */
  18175. Light.prototype.getScaledIntensity = function () {
  18176. return this._photometricScale * this.intensity;
  18177. };
  18178. /**
  18179. * Returns a new Light object, named "name", from the current one.
  18180. * @param name The name of the cloned light
  18181. * @returns the new created light
  18182. */
  18183. Light.prototype.clone = function (name) {
  18184. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18185. if (!constructor) {
  18186. return null;
  18187. }
  18188. return BABYLON.SerializationHelper.Clone(constructor, this);
  18189. };
  18190. /**
  18191. * Serializes the current light into a Serialization object.
  18192. * @returns the serialized object.
  18193. */
  18194. Light.prototype.serialize = function () {
  18195. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18196. // Type
  18197. serializationObject.type = this.getTypeID();
  18198. // Parent
  18199. if (this.parent) {
  18200. serializationObject.parentId = this.parent.id;
  18201. }
  18202. // Inclusion / exclusions
  18203. if (this.excludedMeshes.length > 0) {
  18204. serializationObject.excludedMeshesIds = [];
  18205. this.excludedMeshes.forEach(function (mesh) {
  18206. serializationObject.excludedMeshesIds.push(mesh.id);
  18207. });
  18208. }
  18209. if (this.includedOnlyMeshes.length > 0) {
  18210. serializationObject.includedOnlyMeshesIds = [];
  18211. this.includedOnlyMeshes.forEach(function (mesh) {
  18212. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18213. });
  18214. }
  18215. // Animations
  18216. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18217. serializationObject.ranges = this.serializeAnimationRanges();
  18218. return serializationObject;
  18219. };
  18220. /**
  18221. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18222. * This new light is named "name" and added to the passed scene.
  18223. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18224. * @param name The friendly name of the light
  18225. * @param scene The scene the new light will belong to
  18226. * @returns the constructor function
  18227. */
  18228. Light.GetConstructorFromName = function (type, name, scene) {
  18229. switch (type) {
  18230. case 0:
  18231. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18232. case 1:
  18233. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18234. case 2:
  18235. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18236. case 3:
  18237. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18238. }
  18239. return null;
  18240. };
  18241. /**
  18242. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18243. * @param parsedLight The JSON representation of the light
  18244. * @param scene The scene to create the parsed light in
  18245. * @returns the created light after parsing
  18246. */
  18247. Light.Parse = function (parsedLight, scene) {
  18248. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18249. if (!constructor) {
  18250. return null;
  18251. }
  18252. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18253. // Inclusion / exclusions
  18254. if (parsedLight.excludedMeshesIds) {
  18255. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18256. }
  18257. if (parsedLight.includedOnlyMeshesIds) {
  18258. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18259. }
  18260. // Parent
  18261. if (parsedLight.parentId) {
  18262. light._waitingParentId = parsedLight.parentId;
  18263. }
  18264. // Animations
  18265. if (parsedLight.animations) {
  18266. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18267. var parsedAnimation = parsedLight.animations[animationIndex];
  18268. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18269. }
  18270. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18271. }
  18272. if (parsedLight.autoAnimate) {
  18273. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18274. }
  18275. return light;
  18276. };
  18277. Light.prototype._hookArrayForExcluded = function (array) {
  18278. var _this = this;
  18279. var oldPush = array.push;
  18280. array.push = function () {
  18281. var items = [];
  18282. for (var _i = 0; _i < arguments.length; _i++) {
  18283. items[_i] = arguments[_i];
  18284. }
  18285. var result = oldPush.apply(array, items);
  18286. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18287. var item = items_1[_a];
  18288. item._resyncLighSource(_this);
  18289. }
  18290. return result;
  18291. };
  18292. var oldSplice = array.splice;
  18293. array.splice = function (index, deleteCount) {
  18294. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18295. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18296. var item = deleted_1[_i];
  18297. item._resyncLighSource(_this);
  18298. }
  18299. return deleted;
  18300. };
  18301. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18302. var item = array_1[_i];
  18303. item._resyncLighSource(this);
  18304. }
  18305. };
  18306. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18307. var _this = this;
  18308. var oldPush = array.push;
  18309. array.push = function () {
  18310. var items = [];
  18311. for (var _i = 0; _i < arguments.length; _i++) {
  18312. items[_i] = arguments[_i];
  18313. }
  18314. var result = oldPush.apply(array, items);
  18315. _this._resyncMeshes();
  18316. return result;
  18317. };
  18318. var oldSplice = array.splice;
  18319. array.splice = function (index, deleteCount) {
  18320. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18321. _this._resyncMeshes();
  18322. return deleted;
  18323. };
  18324. this._resyncMeshes();
  18325. };
  18326. Light.prototype._resyncMeshes = function () {
  18327. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18328. var mesh = _a[_i];
  18329. mesh._resyncLighSource(this);
  18330. }
  18331. };
  18332. /**
  18333. * Forces the meshes to update their light related information in their rendering used effects
  18334. * @ignore Internal Use Only
  18335. */
  18336. Light.prototype._markMeshesAsLightDirty = function () {
  18337. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18338. var mesh = _a[_i];
  18339. if (mesh._lightSources.indexOf(this) !== -1) {
  18340. mesh._markSubMeshesAsLightDirty();
  18341. }
  18342. }
  18343. };
  18344. /**
  18345. * Recomputes the cached photometric scale if needed.
  18346. */
  18347. Light.prototype._computePhotometricScale = function () {
  18348. this._photometricScale = this._getPhotometricScale();
  18349. this.getScene().resetCachedMaterial();
  18350. };
  18351. /**
  18352. * Returns the Photometric Scale according to the light type and intensity mode.
  18353. */
  18354. Light.prototype._getPhotometricScale = function () {
  18355. var photometricScale = 0.0;
  18356. var lightTypeID = this.getTypeID();
  18357. //get photometric mode
  18358. var photometricMode = this.intensityMode;
  18359. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18360. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18361. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18362. }
  18363. else {
  18364. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18365. }
  18366. }
  18367. //compute photometric scale
  18368. switch (lightTypeID) {
  18369. case Light.LIGHTTYPEID_POINTLIGHT:
  18370. case Light.LIGHTTYPEID_SPOTLIGHT:
  18371. switch (photometricMode) {
  18372. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18373. photometricScale = 1.0 / (4.0 * Math.PI);
  18374. break;
  18375. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18376. photometricScale = 1.0;
  18377. break;
  18378. case Light.INTENSITYMODE_LUMINANCE:
  18379. photometricScale = this.radius * this.radius;
  18380. break;
  18381. }
  18382. break;
  18383. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18384. switch (photometricMode) {
  18385. case Light.INTENSITYMODE_ILLUMINANCE:
  18386. photometricScale = 1.0;
  18387. break;
  18388. case Light.INTENSITYMODE_LUMINANCE:
  18389. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18390. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18391. var apexAngleRadians = this.radius;
  18392. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18393. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18394. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18395. photometricScale = solidAngle;
  18396. break;
  18397. }
  18398. break;
  18399. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18400. // No fall off in hemisperic light.
  18401. photometricScale = 1.0;
  18402. break;
  18403. }
  18404. return photometricScale;
  18405. };
  18406. /**
  18407. * Reorder the light in the scene according to their defined priority.
  18408. * @ignore Internal Use Only
  18409. */
  18410. Light.prototype._reorderLightsInScene = function () {
  18411. var scene = this.getScene();
  18412. if (this._renderPriority != 0) {
  18413. scene.requireLightSorting = true;
  18414. }
  18415. this.getScene().sortLightsByPriority();
  18416. };
  18417. //lightmapMode Consts
  18418. Light._LIGHTMAP_DEFAULT = 0;
  18419. Light._LIGHTMAP_SPECULAR = 1;
  18420. Light._LIGHTMAP_SHADOWSONLY = 2;
  18421. // Intensity Mode Consts
  18422. Light._INTENSITYMODE_AUTOMATIC = 0;
  18423. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18424. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18425. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18426. Light._INTENSITYMODE_LUMINANCE = 4;
  18427. // Light types ids const.
  18428. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18429. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18430. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18431. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18432. __decorate([
  18433. BABYLON.serializeAsColor3()
  18434. ], Light.prototype, "diffuse", void 0);
  18435. __decorate([
  18436. BABYLON.serializeAsColor3()
  18437. ], Light.prototype, "specular", void 0);
  18438. __decorate([
  18439. BABYLON.serialize()
  18440. ], Light.prototype, "intensity", void 0);
  18441. __decorate([
  18442. BABYLON.serialize()
  18443. ], Light.prototype, "range", void 0);
  18444. __decorate([
  18445. BABYLON.serialize()
  18446. ], Light.prototype, "intensityMode", null);
  18447. __decorate([
  18448. BABYLON.serialize()
  18449. ], Light.prototype, "radius", null);
  18450. __decorate([
  18451. BABYLON.serialize()
  18452. ], Light.prototype, "_renderPriority", void 0);
  18453. __decorate([
  18454. BABYLON.expandToProperty("_reorderLightsInScene")
  18455. ], Light.prototype, "renderPriority", void 0);
  18456. __decorate([
  18457. BABYLON.serialize()
  18458. ], Light.prototype, "shadowEnabled", void 0);
  18459. __decorate([
  18460. BABYLON.serialize("excludeWithLayerMask")
  18461. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18462. __decorate([
  18463. BABYLON.serialize("includeOnlyWithLayerMask")
  18464. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18465. __decorate([
  18466. BABYLON.serialize("lightmapMode")
  18467. ], Light.prototype, "_lightmapMode", void 0);
  18468. return Light;
  18469. }(BABYLON.Node));
  18470. BABYLON.Light = Light;
  18471. })(BABYLON || (BABYLON = {}));
  18472. //# sourceMappingURL=babylon.light.js.map
  18473. var BABYLON;
  18474. (function (BABYLON) {
  18475. var Camera = /** @class */ (function (_super) {
  18476. __extends(Camera, _super);
  18477. function Camera(name, position, scene) {
  18478. var _this = _super.call(this, name, scene) || this;
  18479. /**
  18480. * The vector the camera should consider as up.
  18481. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18482. */
  18483. _this.upVector = BABYLON.Vector3.Up();
  18484. _this.orthoLeft = null;
  18485. _this.orthoRight = null;
  18486. _this.orthoBottom = null;
  18487. _this.orthoTop = null;
  18488. /**
  18489. * FOV is set in Radians. (default is 0.8)
  18490. */
  18491. _this.fov = 0.8;
  18492. _this.minZ = 1;
  18493. _this.maxZ = 10000.0;
  18494. _this.inertia = 0.9;
  18495. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18496. _this.isIntermediate = false;
  18497. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18498. /**
  18499. * Restricts the camera to viewing objects with the same layerMask.
  18500. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18501. */
  18502. _this.layerMask = 0x0FFFFFFF;
  18503. /**
  18504. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18505. */
  18506. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18507. // Camera rig members
  18508. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18509. _this._rigCameras = new Array();
  18510. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18511. _this._skipRendering = false;
  18512. _this.customRenderTargets = new Array();
  18513. // Observables
  18514. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18515. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18516. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18517. _this.onRestoreStateObservable = new BABYLON.Observable();
  18518. // Cache
  18519. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18520. _this._projectionMatrix = new BABYLON.Matrix();
  18521. _this._doNotComputeProjectionMatrix = false;
  18522. _this._postProcesses = new Array();
  18523. _this._transformMatrix = BABYLON.Matrix.Zero();
  18524. _this._activeMeshes = new BABYLON.SmartArray(256);
  18525. _this._globalPosition = BABYLON.Vector3.Zero();
  18526. _this._refreshFrustumPlanes = true;
  18527. _this.getScene().addCamera(_this);
  18528. if (!_this.getScene().activeCamera) {
  18529. _this.getScene().activeCamera = _this;
  18530. }
  18531. _this.position = position;
  18532. return _this;
  18533. }
  18534. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18535. get: function () {
  18536. return Camera._PERSPECTIVE_CAMERA;
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18542. get: function () {
  18543. return Camera._ORTHOGRAPHIC_CAMERA;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18549. /**
  18550. * This is the default FOV mode for perspective cameras.
  18551. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18552. *
  18553. */
  18554. get: function () {
  18555. return Camera._FOVMODE_VERTICAL_FIXED;
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18561. /**
  18562. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18563. *
  18564. */
  18565. get: function () {
  18566. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18567. },
  18568. enumerable: true,
  18569. configurable: true
  18570. });
  18571. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18572. get: function () {
  18573. return Camera._RIG_MODE_NONE;
  18574. },
  18575. enumerable: true,
  18576. configurable: true
  18577. });
  18578. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18579. get: function () {
  18580. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18581. },
  18582. enumerable: true,
  18583. configurable: true
  18584. });
  18585. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18586. get: function () {
  18587. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18593. get: function () {
  18594. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18600. get: function () {
  18601. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18607. get: function () {
  18608. return Camera._RIG_MODE_VR;
  18609. },
  18610. enumerable: true,
  18611. configurable: true
  18612. });
  18613. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18614. get: function () {
  18615. return Camera._RIG_MODE_WEBVR;
  18616. },
  18617. enumerable: true,
  18618. configurable: true
  18619. });
  18620. /**
  18621. * Store current camera state (fov, position, etc..)
  18622. */
  18623. Camera.prototype.storeState = function () {
  18624. this._stateStored = true;
  18625. this._storedFov = this.fov;
  18626. return this;
  18627. };
  18628. /**
  18629. * Restores the camera state values if it has been stored. You must call storeState() first
  18630. */
  18631. Camera.prototype._restoreStateValues = function () {
  18632. if (!this._stateStored) {
  18633. return false;
  18634. }
  18635. this.fov = this._storedFov;
  18636. return true;
  18637. };
  18638. /**
  18639. * Restored camera state. You must call storeState() first
  18640. */
  18641. Camera.prototype.restoreState = function () {
  18642. if (this._restoreStateValues()) {
  18643. this.onRestoreStateObservable.notifyObservers(this);
  18644. return true;
  18645. }
  18646. return false;
  18647. };
  18648. Camera.prototype.getClassName = function () {
  18649. return "Camera";
  18650. };
  18651. /**
  18652. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18653. */
  18654. Camera.prototype.toString = function (fullDetails) {
  18655. var ret = "Name: " + this.name;
  18656. ret += ", type: " + this.getClassName();
  18657. if (this.animations) {
  18658. for (var i = 0; i < this.animations.length; i++) {
  18659. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18660. }
  18661. }
  18662. if (fullDetails) {
  18663. }
  18664. return ret;
  18665. };
  18666. Object.defineProperty(Camera.prototype, "globalPosition", {
  18667. get: function () {
  18668. return this._globalPosition;
  18669. },
  18670. enumerable: true,
  18671. configurable: true
  18672. });
  18673. Camera.prototype.getActiveMeshes = function () {
  18674. return this._activeMeshes;
  18675. };
  18676. Camera.prototype.isActiveMesh = function (mesh) {
  18677. return (this._activeMeshes.indexOf(mesh) !== -1);
  18678. };
  18679. //Cache
  18680. Camera.prototype._initCache = function () {
  18681. _super.prototype._initCache.call(this);
  18682. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18683. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18684. this._cache.mode = undefined;
  18685. this._cache.minZ = undefined;
  18686. this._cache.maxZ = undefined;
  18687. this._cache.fov = undefined;
  18688. this._cache.fovMode = undefined;
  18689. this._cache.aspectRatio = undefined;
  18690. this._cache.orthoLeft = undefined;
  18691. this._cache.orthoRight = undefined;
  18692. this._cache.orthoBottom = undefined;
  18693. this._cache.orthoTop = undefined;
  18694. this._cache.renderWidth = undefined;
  18695. this._cache.renderHeight = undefined;
  18696. };
  18697. Camera.prototype._updateCache = function (ignoreParentClass) {
  18698. if (!ignoreParentClass) {
  18699. _super.prototype._updateCache.call(this);
  18700. }
  18701. this._cache.position.copyFrom(this.position);
  18702. this._cache.upVector.copyFrom(this.upVector);
  18703. };
  18704. // Synchronized
  18705. Camera.prototype._isSynchronized = function () {
  18706. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18707. };
  18708. Camera.prototype._isSynchronizedViewMatrix = function () {
  18709. if (!_super.prototype._isSynchronized.call(this))
  18710. return false;
  18711. return this._cache.position.equals(this.position)
  18712. && this._cache.upVector.equals(this.upVector)
  18713. && this.isSynchronizedWithParent();
  18714. };
  18715. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18716. var check = this._cache.mode === this.mode
  18717. && this._cache.minZ === this.minZ
  18718. && this._cache.maxZ === this.maxZ;
  18719. if (!check) {
  18720. return false;
  18721. }
  18722. var engine = this.getEngine();
  18723. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18724. check = this._cache.fov === this.fov
  18725. && this._cache.fovMode === this.fovMode
  18726. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18727. }
  18728. else {
  18729. check = this._cache.orthoLeft === this.orthoLeft
  18730. && this._cache.orthoRight === this.orthoRight
  18731. && this._cache.orthoBottom === this.orthoBottom
  18732. && this._cache.orthoTop === this.orthoTop
  18733. && this._cache.renderWidth === engine.getRenderWidth()
  18734. && this._cache.renderHeight === engine.getRenderHeight();
  18735. }
  18736. return check;
  18737. };
  18738. // Controls
  18739. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18740. };
  18741. Camera.prototype.detachControl = function (element) {
  18742. };
  18743. Camera.prototype.update = function () {
  18744. this._checkInputs();
  18745. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18746. this._updateRigCameras();
  18747. }
  18748. };
  18749. Camera.prototype._checkInputs = function () {
  18750. this.onAfterCheckInputsObservable.notifyObservers(this);
  18751. };
  18752. Object.defineProperty(Camera.prototype, "rigCameras", {
  18753. get: function () {
  18754. return this._rigCameras;
  18755. },
  18756. enumerable: true,
  18757. configurable: true
  18758. });
  18759. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18760. get: function () {
  18761. return this._rigPostProcess;
  18762. },
  18763. enumerable: true,
  18764. configurable: true
  18765. });
  18766. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18767. // invalidate framebuffer
  18768. if (this._postProcesses.length > 0) {
  18769. this._postProcesses[0].markTextureDirty();
  18770. }
  18771. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18772. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18773. var cam = this._rigCameras[i];
  18774. var rigPostProcess = cam._rigPostProcess;
  18775. // for VR rig, there does not have to be a post process
  18776. if (rigPostProcess) {
  18777. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18778. if (isPass) {
  18779. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18780. cam.isIntermediate = this._postProcesses.length === 0;
  18781. }
  18782. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18783. rigPostProcess.markTextureDirty();
  18784. }
  18785. else {
  18786. cam._postProcesses = this._postProcesses.slice(0);
  18787. }
  18788. }
  18789. };
  18790. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18791. if (insertAt === void 0) { insertAt = null; }
  18792. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18793. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18794. return 0;
  18795. }
  18796. if (insertAt == null || insertAt < 0) {
  18797. this._postProcesses.push(postProcess);
  18798. }
  18799. else {
  18800. this._postProcesses.splice(insertAt, 0, postProcess);
  18801. }
  18802. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18803. return this._postProcesses.indexOf(postProcess);
  18804. };
  18805. Camera.prototype.detachPostProcess = function (postProcess) {
  18806. var idx = this._postProcesses.indexOf(postProcess);
  18807. if (idx !== -1) {
  18808. this._postProcesses.splice(idx, 1);
  18809. }
  18810. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18811. };
  18812. Camera.prototype.getWorldMatrix = function () {
  18813. if (!this._worldMatrix) {
  18814. this._worldMatrix = BABYLON.Matrix.Identity();
  18815. }
  18816. var viewMatrix = this.getViewMatrix();
  18817. viewMatrix.invertToRef(this._worldMatrix);
  18818. return this._worldMatrix;
  18819. };
  18820. Camera.prototype._getViewMatrix = function () {
  18821. return BABYLON.Matrix.Identity();
  18822. };
  18823. Camera.prototype.getViewMatrix = function (force) {
  18824. if (!force && this._isSynchronizedViewMatrix()) {
  18825. return this._computedViewMatrix;
  18826. }
  18827. this.updateCache();
  18828. this._computedViewMatrix = this._getViewMatrix();
  18829. this._currentRenderId = this.getScene().getRenderId();
  18830. this._refreshFrustumPlanes = true;
  18831. if (!this.parent || !this.parent.getWorldMatrix) {
  18832. this._globalPosition.copyFrom(this.position);
  18833. }
  18834. else {
  18835. if (!this._worldMatrix) {
  18836. this._worldMatrix = BABYLON.Matrix.Identity();
  18837. }
  18838. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18839. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18840. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18841. this._computedViewMatrix.invert();
  18842. this._markSyncedWithParent();
  18843. }
  18844. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18845. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18846. }
  18847. this.onViewMatrixChangedObservable.notifyObservers(this);
  18848. return this._computedViewMatrix;
  18849. };
  18850. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18851. this._doNotComputeProjectionMatrix = true;
  18852. if (projection !== undefined) {
  18853. this._projectionMatrix = projection;
  18854. }
  18855. };
  18856. ;
  18857. Camera.prototype.unfreezeProjectionMatrix = function () {
  18858. this._doNotComputeProjectionMatrix = false;
  18859. };
  18860. ;
  18861. Camera.prototype.getProjectionMatrix = function (force) {
  18862. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18863. return this._projectionMatrix;
  18864. }
  18865. // Cache
  18866. this._cache.mode = this.mode;
  18867. this._cache.minZ = this.minZ;
  18868. this._cache.maxZ = this.maxZ;
  18869. // Matrix
  18870. this._refreshFrustumPlanes = true;
  18871. var engine = this.getEngine();
  18872. var scene = this.getScene();
  18873. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18874. this._cache.fov = this.fov;
  18875. this._cache.fovMode = this.fovMode;
  18876. this._cache.aspectRatio = engine.getAspectRatio(this);
  18877. if (this.minZ <= 0) {
  18878. this.minZ = 0.1;
  18879. }
  18880. if (scene.useRightHandedSystem) {
  18881. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18882. }
  18883. else {
  18884. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18885. }
  18886. }
  18887. else {
  18888. var halfWidth = engine.getRenderWidth() / 2.0;
  18889. var halfHeight = engine.getRenderHeight() / 2.0;
  18890. if (scene.useRightHandedSystem) {
  18891. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18892. }
  18893. else {
  18894. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18895. }
  18896. this._cache.orthoLeft = this.orthoLeft;
  18897. this._cache.orthoRight = this.orthoRight;
  18898. this._cache.orthoBottom = this.orthoBottom;
  18899. this._cache.orthoTop = this.orthoTop;
  18900. this._cache.renderWidth = engine.getRenderWidth();
  18901. this._cache.renderHeight = engine.getRenderHeight();
  18902. }
  18903. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18904. return this._projectionMatrix;
  18905. };
  18906. Camera.prototype.getTranformationMatrix = function () {
  18907. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18908. return this._transformMatrix;
  18909. };
  18910. Camera.prototype.updateFrustumPlanes = function () {
  18911. if (!this._refreshFrustumPlanes) {
  18912. return;
  18913. }
  18914. this.getTranformationMatrix();
  18915. if (!this._frustumPlanes) {
  18916. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18917. }
  18918. else {
  18919. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18920. }
  18921. this._refreshFrustumPlanes = false;
  18922. };
  18923. Camera.prototype.isInFrustum = function (target) {
  18924. this.updateFrustumPlanes();
  18925. return target.isInFrustum(this._frustumPlanes);
  18926. };
  18927. Camera.prototype.isCompletelyInFrustum = function (target) {
  18928. this.updateFrustumPlanes();
  18929. return target.isCompletelyInFrustum(this._frustumPlanes);
  18930. };
  18931. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18932. if (length === void 0) { length = 100; }
  18933. if (!transform) {
  18934. transform = this.getWorldMatrix();
  18935. }
  18936. if (!origin) {
  18937. origin = this.position;
  18938. }
  18939. var forward = new BABYLON.Vector3(0, 0, 1);
  18940. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18941. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18942. return new BABYLON.Ray(origin, direction, length);
  18943. };
  18944. Camera.prototype.dispose = function () {
  18945. // Observables
  18946. this.onViewMatrixChangedObservable.clear();
  18947. this.onProjectionMatrixChangedObservable.clear();
  18948. this.onAfterCheckInputsObservable.clear();
  18949. this.onRestoreStateObservable.clear();
  18950. // Inputs
  18951. if (this.inputs) {
  18952. this.inputs.clear();
  18953. }
  18954. // Animations
  18955. this.getScene().stopAnimation(this);
  18956. // Remove from scene
  18957. this.getScene().removeCamera(this);
  18958. while (this._rigCameras.length > 0) {
  18959. var camera = this._rigCameras.pop();
  18960. if (camera) {
  18961. camera.dispose();
  18962. }
  18963. }
  18964. // Postprocesses
  18965. if (this._rigPostProcess) {
  18966. this._rigPostProcess.dispose(this);
  18967. this._rigPostProcess = null;
  18968. this._postProcesses = [];
  18969. }
  18970. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18971. this._rigPostProcess = null;
  18972. this._postProcesses = [];
  18973. }
  18974. else {
  18975. var i = this._postProcesses.length;
  18976. while (--i >= 0) {
  18977. this._postProcesses[i].dispose(this);
  18978. }
  18979. }
  18980. // Render targets
  18981. var i = this.customRenderTargets.length;
  18982. while (--i >= 0) {
  18983. this.customRenderTargets[i].dispose();
  18984. }
  18985. this.customRenderTargets = [];
  18986. // Active Meshes
  18987. this._activeMeshes.dispose();
  18988. _super.prototype.dispose.call(this);
  18989. };
  18990. Object.defineProperty(Camera.prototype, "leftCamera", {
  18991. // ---- Camera rigs section ----
  18992. get: function () {
  18993. if (this._rigCameras.length < 1) {
  18994. return null;
  18995. }
  18996. return this._rigCameras[0];
  18997. },
  18998. enumerable: true,
  18999. configurable: true
  19000. });
  19001. Object.defineProperty(Camera.prototype, "rightCamera", {
  19002. get: function () {
  19003. if (this._rigCameras.length < 2) {
  19004. return null;
  19005. }
  19006. return this._rigCameras[1];
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Camera.prototype.getLeftTarget = function () {
  19012. if (this._rigCameras.length < 1) {
  19013. return null;
  19014. }
  19015. return this._rigCameras[0].getTarget();
  19016. };
  19017. Camera.prototype.getRightTarget = function () {
  19018. if (this._rigCameras.length < 2) {
  19019. return null;
  19020. }
  19021. return this._rigCameras[1].getTarget();
  19022. };
  19023. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19024. if (this.cameraRigMode === mode) {
  19025. return;
  19026. }
  19027. while (this._rigCameras.length > 0) {
  19028. var camera = this._rigCameras.pop();
  19029. if (camera) {
  19030. camera.dispose();
  19031. }
  19032. }
  19033. this.cameraRigMode = mode;
  19034. this._cameraRigParams = {};
  19035. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19036. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19037. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19038. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19039. // create the rig cameras, unless none
  19040. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19041. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19042. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19043. if (leftCamera && rightCamera) {
  19044. this._rigCameras.push(leftCamera);
  19045. this._rigCameras.push(rightCamera);
  19046. }
  19047. }
  19048. switch (this.cameraRigMode) {
  19049. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19050. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19051. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19052. break;
  19053. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19054. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19055. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19056. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19057. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19058. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19059. break;
  19060. case Camera.RIG_MODE_VR:
  19061. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19062. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19063. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19064. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19065. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19066. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19067. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19068. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19069. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19070. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19071. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19072. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19073. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19074. if (metrics.compensateDistortion) {
  19075. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19076. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19077. }
  19078. break;
  19079. case Camera.RIG_MODE_WEBVR:
  19080. if (rigParams.vrDisplay) {
  19081. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19082. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19083. //Left eye
  19084. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19085. this._rigCameras[0].setCameraRigParameter("left", true);
  19086. //leaving this for future reference
  19087. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19088. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19089. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19090. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19091. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19092. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19093. this._rigCameras[0].parent = this;
  19094. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19095. //Right eye
  19096. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19097. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19098. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19099. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19100. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19101. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19102. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19103. this._rigCameras[1].parent = this;
  19104. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19105. if (Camera.UseAlternateWebVRRendering) {
  19106. this._rigCameras[1]._skipRendering = true;
  19107. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19108. }
  19109. }
  19110. break;
  19111. }
  19112. this._cascadePostProcessesToRigCams();
  19113. this.update();
  19114. };
  19115. Camera.prototype._getVRProjectionMatrix = function () {
  19116. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19117. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19118. return this._projectionMatrix;
  19119. };
  19120. Camera.prototype._updateCameraRotationMatrix = function () {
  19121. //Here for WebVR
  19122. };
  19123. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19124. //Here for WebVR
  19125. };
  19126. /**
  19127. * This function MUST be overwritten by the different WebVR cameras available.
  19128. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19129. */
  19130. Camera.prototype._getWebVRProjectionMatrix = function () {
  19131. return BABYLON.Matrix.Identity();
  19132. };
  19133. /**
  19134. * This function MUST be overwritten by the different WebVR cameras available.
  19135. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19136. */
  19137. Camera.prototype._getWebVRViewMatrix = function () {
  19138. return BABYLON.Matrix.Identity();
  19139. };
  19140. Camera.prototype.setCameraRigParameter = function (name, value) {
  19141. if (!this._cameraRigParams) {
  19142. this._cameraRigParams = {};
  19143. }
  19144. this._cameraRigParams[name] = value;
  19145. //provisionnally:
  19146. if (name === "interaxialDistance") {
  19147. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19148. }
  19149. };
  19150. /**
  19151. * needs to be overridden by children so sub has required properties to be copied
  19152. */
  19153. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19154. return null;
  19155. };
  19156. /**
  19157. * May need to be overridden by children
  19158. */
  19159. Camera.prototype._updateRigCameras = function () {
  19160. for (var i = 0; i < this._rigCameras.length; i++) {
  19161. this._rigCameras[i].minZ = this.minZ;
  19162. this._rigCameras[i].maxZ = this.maxZ;
  19163. this._rigCameras[i].fov = this.fov;
  19164. }
  19165. // only update viewport when ANAGLYPH
  19166. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19167. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19168. }
  19169. };
  19170. Camera.prototype._setupInputs = function () {
  19171. };
  19172. Camera.prototype.serialize = function () {
  19173. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19174. // Type
  19175. serializationObject.type = this.getClassName();
  19176. // Parent
  19177. if (this.parent) {
  19178. serializationObject.parentId = this.parent.id;
  19179. }
  19180. if (this.inputs) {
  19181. this.inputs.serialize(serializationObject);
  19182. }
  19183. // Animations
  19184. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19185. serializationObject.ranges = this.serializeAnimationRanges();
  19186. return serializationObject;
  19187. };
  19188. Camera.prototype.clone = function (name) {
  19189. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19190. };
  19191. Camera.prototype.getDirection = function (localAxis) {
  19192. var result = BABYLON.Vector3.Zero();
  19193. this.getDirectionToRef(localAxis, result);
  19194. return result;
  19195. };
  19196. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19197. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19198. };
  19199. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19200. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19201. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19202. switch (type) {
  19203. case "ArcRotateCamera":
  19204. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19205. case "DeviceOrientationCamera":
  19206. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19207. case "FollowCamera":
  19208. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19209. case "ArcFollowCamera":
  19210. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19211. case "GamepadCamera":
  19212. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19213. case "TouchCamera":
  19214. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19215. case "VirtualJoysticksCamera":
  19216. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19217. case "WebVRFreeCamera":
  19218. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19219. case "WebVRGamepadCamera":
  19220. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19221. case "VRDeviceOrientationFreeCamera":
  19222. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19223. case "VRDeviceOrientationGamepadCamera":
  19224. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19225. case "AnaglyphArcRotateCamera":
  19226. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19227. case "AnaglyphFreeCamera":
  19228. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19229. case "AnaglyphGamepadCamera":
  19230. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19231. case "AnaglyphUniversalCamera":
  19232. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19233. case "StereoscopicArcRotateCamera":
  19234. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19235. case "StereoscopicFreeCamera":
  19236. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19237. case "StereoscopicGamepadCamera":
  19238. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19239. case "StereoscopicUniversalCamera":
  19240. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19241. case "FreeCamera":// Forcing Universal here
  19242. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19243. default:// Universal Camera is the default value
  19244. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19245. }
  19246. };
  19247. Camera.prototype.computeWorldMatrix = function () {
  19248. return this.getWorldMatrix();
  19249. };
  19250. Camera.Parse = function (parsedCamera, scene) {
  19251. var type = parsedCamera.type;
  19252. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19253. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19254. // Parent
  19255. if (parsedCamera.parentId) {
  19256. camera._waitingParentId = parsedCamera.parentId;
  19257. }
  19258. //If camera has an input manager, let it parse inputs settings
  19259. if (camera.inputs) {
  19260. camera.inputs.parse(parsedCamera);
  19261. camera._setupInputs();
  19262. }
  19263. if (camera.setPosition) {
  19264. camera.position.copyFromFloats(0, 0, 0);
  19265. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19266. }
  19267. // Target
  19268. if (parsedCamera.target) {
  19269. if (camera.setTarget) {
  19270. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19271. }
  19272. }
  19273. // Apply 3d rig, when found
  19274. if (parsedCamera.cameraRigMode) {
  19275. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19276. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19277. }
  19278. // Animations
  19279. if (parsedCamera.animations) {
  19280. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19281. var parsedAnimation = parsedCamera.animations[animationIndex];
  19282. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19283. }
  19284. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19285. }
  19286. if (parsedCamera.autoAnimate) {
  19287. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19288. }
  19289. return camera;
  19290. };
  19291. // Statics
  19292. Camera._PERSPECTIVE_CAMERA = 0;
  19293. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19294. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19295. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19296. Camera._RIG_MODE_NONE = 0;
  19297. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19298. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19299. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19300. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19301. Camera._RIG_MODE_VR = 20;
  19302. Camera._RIG_MODE_WEBVR = 21;
  19303. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19304. Camera.UseAlternateWebVRRendering = false;
  19305. __decorate([
  19306. BABYLON.serializeAsVector3()
  19307. ], Camera.prototype, "position", void 0);
  19308. __decorate([
  19309. BABYLON.serializeAsVector3()
  19310. ], Camera.prototype, "upVector", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], Camera.prototype, "orthoLeft", void 0);
  19314. __decorate([
  19315. BABYLON.serialize()
  19316. ], Camera.prototype, "orthoRight", void 0);
  19317. __decorate([
  19318. BABYLON.serialize()
  19319. ], Camera.prototype, "orthoBottom", void 0);
  19320. __decorate([
  19321. BABYLON.serialize()
  19322. ], Camera.prototype, "orthoTop", void 0);
  19323. __decorate([
  19324. BABYLON.serialize()
  19325. ], Camera.prototype, "fov", void 0);
  19326. __decorate([
  19327. BABYLON.serialize()
  19328. ], Camera.prototype, "minZ", void 0);
  19329. __decorate([
  19330. BABYLON.serialize()
  19331. ], Camera.prototype, "maxZ", void 0);
  19332. __decorate([
  19333. BABYLON.serialize()
  19334. ], Camera.prototype, "inertia", void 0);
  19335. __decorate([
  19336. BABYLON.serialize()
  19337. ], Camera.prototype, "mode", void 0);
  19338. __decorate([
  19339. BABYLON.serialize()
  19340. ], Camera.prototype, "layerMask", void 0);
  19341. __decorate([
  19342. BABYLON.serialize()
  19343. ], Camera.prototype, "fovMode", void 0);
  19344. __decorate([
  19345. BABYLON.serialize()
  19346. ], Camera.prototype, "cameraRigMode", void 0);
  19347. __decorate([
  19348. BABYLON.serialize()
  19349. ], Camera.prototype, "interaxialDistance", void 0);
  19350. __decorate([
  19351. BABYLON.serialize()
  19352. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19353. return Camera;
  19354. }(BABYLON.Node));
  19355. BABYLON.Camera = Camera;
  19356. })(BABYLON || (BABYLON = {}));
  19357. //# sourceMappingURL=babylon.camera.js.map
  19358. var BABYLON;
  19359. (function (BABYLON) {
  19360. var RenderingManager = /** @class */ (function () {
  19361. function RenderingManager(scene) {
  19362. this._renderingGroups = new Array();
  19363. this._autoClearDepthStencil = {};
  19364. this._customOpaqueSortCompareFn = {};
  19365. this._customAlphaTestSortCompareFn = {};
  19366. this._customTransparentSortCompareFn = {};
  19367. this._renderinGroupInfo = null;
  19368. this._scene = scene;
  19369. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19370. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19371. }
  19372. }
  19373. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19374. if (depth === void 0) { depth = true; }
  19375. if (stencil === void 0) { stencil = true; }
  19376. if (this._depthStencilBufferAlreadyCleaned) {
  19377. return;
  19378. }
  19379. this._scene.getEngine().clear(null, false, depth, stencil);
  19380. this._depthStencilBufferAlreadyCleaned = true;
  19381. };
  19382. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19383. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19384. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19385. var info = null;
  19386. if (observable) {
  19387. if (!this._renderinGroupInfo) {
  19388. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19389. }
  19390. info = this._renderinGroupInfo;
  19391. info.scene = this._scene;
  19392. info.camera = this._scene.activeCamera;
  19393. }
  19394. // Dispatch sprites
  19395. if (renderSprites) {
  19396. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19397. var manager = this._scene.spriteManagers[index];
  19398. this.dispatchSprites(manager);
  19399. }
  19400. }
  19401. // Render
  19402. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19403. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19404. var renderingGroup = this._renderingGroups[index];
  19405. if (!renderingGroup && !observable)
  19406. continue;
  19407. var renderingGroupMask = 0;
  19408. // Fire PRECLEAR stage
  19409. if (observable && info) {
  19410. renderingGroupMask = Math.pow(2, index);
  19411. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19412. info.renderingGroupId = index;
  19413. observable.notifyObservers(info, renderingGroupMask);
  19414. }
  19415. // Clear depth/stencil if needed
  19416. if (RenderingManager.AUTOCLEAR) {
  19417. var autoClear = this._autoClearDepthStencil[index];
  19418. if (autoClear && autoClear.autoClear) {
  19419. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19420. }
  19421. }
  19422. if (observable && info) {
  19423. // Fire PREOPAQUE stage
  19424. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19425. observable.notifyObservers(info, renderingGroupMask);
  19426. // Fire PRETRANSPARENT stage
  19427. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19428. observable.notifyObservers(info, renderingGroupMask);
  19429. }
  19430. if (renderingGroup)
  19431. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19432. // Fire POSTTRANSPARENT stage
  19433. if (observable && info) {
  19434. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19435. observable.notifyObservers(info, renderingGroupMask);
  19436. }
  19437. }
  19438. };
  19439. RenderingManager.prototype.reset = function () {
  19440. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19441. var renderingGroup = this._renderingGroups[index];
  19442. if (renderingGroup) {
  19443. renderingGroup.prepare();
  19444. }
  19445. }
  19446. };
  19447. RenderingManager.prototype.dispose = function () {
  19448. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19449. var renderingGroup = this._renderingGroups[index];
  19450. if (renderingGroup) {
  19451. renderingGroup.dispose();
  19452. }
  19453. }
  19454. this._renderingGroups.length = 0;
  19455. };
  19456. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19457. if (this._renderingGroups[renderingGroupId] === undefined) {
  19458. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19459. }
  19460. };
  19461. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19462. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19463. this._prepareRenderingGroup(renderingGroupId);
  19464. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19465. };
  19466. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19467. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19468. this._prepareRenderingGroup(renderingGroupId);
  19469. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19470. };
  19471. /**
  19472. * @param subMesh The submesh to dispatch
  19473. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19474. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19475. */
  19476. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19477. if (mesh === undefined) {
  19478. mesh = subMesh.getMesh();
  19479. }
  19480. var renderingGroupId = mesh.renderingGroupId || 0;
  19481. this._prepareRenderingGroup(renderingGroupId);
  19482. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19483. };
  19484. /**
  19485. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19486. * This allowed control for front to back rendering or reversly depending of the special needs.
  19487. *
  19488. * @param renderingGroupId The rendering group id corresponding to its index
  19489. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19490. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19491. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19492. */
  19493. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19494. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19495. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19496. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19497. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19498. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19499. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19500. if (this._renderingGroups[renderingGroupId]) {
  19501. var group = this._renderingGroups[renderingGroupId];
  19502. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19503. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19504. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19505. }
  19506. };
  19507. /**
  19508. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19509. *
  19510. * @param renderingGroupId The rendering group id corresponding to its index
  19511. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19512. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19513. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19514. */
  19515. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19516. if (depth === void 0) { depth = true; }
  19517. if (stencil === void 0) { stencil = true; }
  19518. this._autoClearDepthStencil[renderingGroupId] = {
  19519. autoClear: autoClearDepthStencil,
  19520. depth: depth,
  19521. stencil: stencil
  19522. };
  19523. };
  19524. /**
  19525. * The max id used for rendering groups (not included)
  19526. */
  19527. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19528. /**
  19529. * The min id used for rendering groups (included)
  19530. */
  19531. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19532. /**
  19533. * Used to globally prevent autoclearing scenes.
  19534. */
  19535. RenderingManager.AUTOCLEAR = true;
  19536. return RenderingManager;
  19537. }());
  19538. BABYLON.RenderingManager = RenderingManager;
  19539. })(BABYLON || (BABYLON = {}));
  19540. //# sourceMappingURL=babylon.renderingManager.js.map
  19541. var BABYLON;
  19542. (function (BABYLON) {
  19543. var RenderingGroup = /** @class */ (function () {
  19544. /**
  19545. * Creates a new rendering group.
  19546. * @param index The rendering group index
  19547. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19548. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19549. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19550. */
  19551. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19552. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19553. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19554. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19555. this.index = index;
  19556. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19557. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19558. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19559. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19560. this._particleSystems = new BABYLON.SmartArray(256);
  19561. this._spriteManagers = new BABYLON.SmartArray(256);
  19562. this._edgesRenderers = new BABYLON.SmartArray(16);
  19563. this._scene = scene;
  19564. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19565. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19566. this.transparentSortCompareFn = transparentSortCompareFn;
  19567. }
  19568. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19569. /**
  19570. * Set the opaque sort comparison function.
  19571. * If null the sub meshes will be render in the order they were created
  19572. */
  19573. set: function (value) {
  19574. this._opaqueSortCompareFn = value;
  19575. if (value) {
  19576. this._renderOpaque = this.renderOpaqueSorted;
  19577. }
  19578. else {
  19579. this._renderOpaque = RenderingGroup.renderUnsorted;
  19580. }
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19586. /**
  19587. * Set the alpha test sort comparison function.
  19588. * If null the sub meshes will be render in the order they were created
  19589. */
  19590. set: function (value) {
  19591. this._alphaTestSortCompareFn = value;
  19592. if (value) {
  19593. this._renderAlphaTest = this.renderAlphaTestSorted;
  19594. }
  19595. else {
  19596. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19597. }
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19603. /**
  19604. * Set the transparent sort comparison function.
  19605. * If null the sub meshes will be render in the order they were created
  19606. */
  19607. set: function (value) {
  19608. if (value) {
  19609. this._transparentSortCompareFn = value;
  19610. }
  19611. else {
  19612. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19613. }
  19614. this._renderTransparent = this.renderTransparentSorted;
  19615. },
  19616. enumerable: true,
  19617. configurable: true
  19618. });
  19619. /**
  19620. * Render all the sub meshes contained in the group.
  19621. * @param customRenderFunction Used to override the default render behaviour of the group.
  19622. * @returns true if rendered some submeshes.
  19623. */
  19624. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19625. if (customRenderFunction) {
  19626. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19627. return;
  19628. }
  19629. var engine = this._scene.getEngine();
  19630. // Depth only
  19631. if (this._depthOnlySubMeshes.length !== 0) {
  19632. engine.setColorWrite(false);
  19633. this._renderAlphaTest(this._depthOnlySubMeshes);
  19634. engine.setColorWrite(true);
  19635. }
  19636. // Opaque
  19637. if (this._opaqueSubMeshes.length !== 0) {
  19638. this._renderOpaque(this._opaqueSubMeshes);
  19639. }
  19640. // Alpha test
  19641. if (this._alphaTestSubMeshes.length !== 0) {
  19642. this._renderAlphaTest(this._alphaTestSubMeshes);
  19643. }
  19644. var stencilState = engine.getStencilBuffer();
  19645. engine.setStencilBuffer(false);
  19646. // Sprites
  19647. if (renderSprites) {
  19648. this._renderSprites();
  19649. }
  19650. // Particles
  19651. if (renderParticles) {
  19652. this._renderParticles(activeMeshes);
  19653. }
  19654. if (this.onBeforeTransparentRendering) {
  19655. this.onBeforeTransparentRendering();
  19656. }
  19657. // Transparent
  19658. if (this._transparentSubMeshes.length !== 0) {
  19659. this._renderTransparent(this._transparentSubMeshes);
  19660. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19661. }
  19662. // Set back stencil to false in case it changes before the edge renderer.
  19663. engine.setStencilBuffer(false);
  19664. // Edges
  19665. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19666. this._edgesRenderers.data[edgesRendererIndex].render();
  19667. }
  19668. // Restore Stencil state.
  19669. engine.setStencilBuffer(stencilState);
  19670. };
  19671. /**
  19672. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19673. * @param subMeshes The submeshes to render
  19674. */
  19675. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19676. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19677. };
  19678. /**
  19679. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19680. * @param subMeshes The submeshes to render
  19681. */
  19682. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19683. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19684. };
  19685. /**
  19686. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19687. * @param subMeshes The submeshes to render
  19688. */
  19689. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19690. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19691. };
  19692. /**
  19693. * Renders the submeshes in a specified order.
  19694. * @param subMeshes The submeshes to sort before render
  19695. * @param sortCompareFn The comparison function use to sort
  19696. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19697. * @param transparent Specifies to activate blending if true
  19698. */
  19699. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19700. var subIndex = 0;
  19701. var subMesh;
  19702. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19703. for (; subIndex < subMeshes.length; subIndex++) {
  19704. subMesh = subMeshes.data[subIndex];
  19705. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19706. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19707. }
  19708. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19709. if (sortCompareFn) {
  19710. sortedArray.sort(sortCompareFn);
  19711. }
  19712. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19713. subMesh = sortedArray[subIndex];
  19714. if (transparent) {
  19715. var material = subMesh.getMaterial();
  19716. if (material && material.needDepthPrePass) {
  19717. var engine = material.getScene().getEngine();
  19718. engine.setColorWrite(false);
  19719. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19720. subMesh.render(false);
  19721. engine.setColorWrite(true);
  19722. }
  19723. }
  19724. subMesh.render(transparent);
  19725. }
  19726. };
  19727. /**
  19728. * Renders the submeshes in the order they were dispatched (no sort applied).
  19729. * @param subMeshes The submeshes to render
  19730. */
  19731. RenderingGroup.renderUnsorted = function (subMeshes) {
  19732. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19733. var submesh = subMeshes.data[subIndex];
  19734. submesh.render(false);
  19735. }
  19736. };
  19737. /**
  19738. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19739. * are rendered back to front if in the same alpha index.
  19740. *
  19741. * @param a The first submesh
  19742. * @param b The second submesh
  19743. * @returns The result of the comparison
  19744. */
  19745. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19746. // Alpha index first
  19747. if (a._alphaIndex > b._alphaIndex) {
  19748. return 1;
  19749. }
  19750. if (a._alphaIndex < b._alphaIndex) {
  19751. return -1;
  19752. }
  19753. // Then distance to camera
  19754. return RenderingGroup.backToFrontSortCompare(a, b);
  19755. };
  19756. /**
  19757. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19758. * are rendered back to front.
  19759. *
  19760. * @param a The first submesh
  19761. * @param b The second submesh
  19762. * @returns The result of the comparison
  19763. */
  19764. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19765. // Then distance to camera
  19766. if (a._distanceToCamera < b._distanceToCamera) {
  19767. return 1;
  19768. }
  19769. if (a._distanceToCamera > b._distanceToCamera) {
  19770. return -1;
  19771. }
  19772. return 0;
  19773. };
  19774. /**
  19775. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19776. * are rendered front to back (prevent overdraw).
  19777. *
  19778. * @param a The first submesh
  19779. * @param b The second submesh
  19780. * @returns The result of the comparison
  19781. */
  19782. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19783. // Then distance to camera
  19784. if (a._distanceToCamera < b._distanceToCamera) {
  19785. return -1;
  19786. }
  19787. if (a._distanceToCamera > b._distanceToCamera) {
  19788. return 1;
  19789. }
  19790. return 0;
  19791. };
  19792. /**
  19793. * Resets the different lists of submeshes to prepare a new frame.
  19794. */
  19795. RenderingGroup.prototype.prepare = function () {
  19796. this._opaqueSubMeshes.reset();
  19797. this._transparentSubMeshes.reset();
  19798. this._alphaTestSubMeshes.reset();
  19799. this._depthOnlySubMeshes.reset();
  19800. this._particleSystems.reset();
  19801. this._spriteManagers.reset();
  19802. this._edgesRenderers.reset();
  19803. };
  19804. RenderingGroup.prototype.dispose = function () {
  19805. this._opaqueSubMeshes.dispose();
  19806. this._transparentSubMeshes.dispose();
  19807. this._alphaTestSubMeshes.dispose();
  19808. this._depthOnlySubMeshes.dispose();
  19809. this._particleSystems.dispose();
  19810. this._spriteManagers.dispose();
  19811. this._edgesRenderers.dispose();
  19812. };
  19813. /**
  19814. * Inserts the submesh in its correct queue depending on its material.
  19815. * @param subMesh The submesh to dispatch
  19816. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19817. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19818. */
  19819. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19820. // Get mesh and materials if not provided
  19821. if (mesh === undefined) {
  19822. mesh = subMesh.getMesh();
  19823. }
  19824. if (material === undefined) {
  19825. material = subMesh.getMaterial();
  19826. }
  19827. if (material === null || material === undefined) {
  19828. return;
  19829. }
  19830. if (material.needAlphaBlendingForMesh(mesh)) {
  19831. this._transparentSubMeshes.push(subMesh);
  19832. }
  19833. else if (material.needAlphaTesting()) {
  19834. if (material.needDepthPrePass) {
  19835. this._depthOnlySubMeshes.push(subMesh);
  19836. }
  19837. this._alphaTestSubMeshes.push(subMesh);
  19838. }
  19839. else {
  19840. if (material.needDepthPrePass) {
  19841. this._depthOnlySubMeshes.push(subMesh);
  19842. }
  19843. this._opaqueSubMeshes.push(subMesh); // Opaque
  19844. }
  19845. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19846. this._edgesRenderers.push(mesh._edgesRenderer);
  19847. }
  19848. };
  19849. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19850. this._spriteManagers.push(spriteManager);
  19851. };
  19852. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19853. this._particleSystems.push(particleSystem);
  19854. };
  19855. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19856. if (this._particleSystems.length === 0) {
  19857. return;
  19858. }
  19859. // Particles
  19860. var activeCamera = this._scene.activeCamera;
  19861. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19862. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19863. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19864. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19865. continue;
  19866. }
  19867. var emitter = particleSystem.emitter;
  19868. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19869. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19870. }
  19871. }
  19872. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19873. };
  19874. RenderingGroup.prototype._renderSprites = function () {
  19875. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19876. return;
  19877. }
  19878. // Sprites
  19879. var activeCamera = this._scene.activeCamera;
  19880. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19881. for (var id = 0; id < this._spriteManagers.length; id++) {
  19882. var spriteManager = this._spriteManagers.data[id];
  19883. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19884. spriteManager.render();
  19885. }
  19886. }
  19887. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19888. };
  19889. return RenderingGroup;
  19890. }());
  19891. BABYLON.RenderingGroup = RenderingGroup;
  19892. })(BABYLON || (BABYLON = {}));
  19893. //# sourceMappingURL=babylon.renderingGroup.js.map
  19894. var BABYLON;
  19895. (function (BABYLON) {
  19896. var ClickInfo = /** @class */ (function () {
  19897. function ClickInfo() {
  19898. this._singleClick = false;
  19899. this._doubleClick = false;
  19900. this._hasSwiped = false;
  19901. this._ignore = false;
  19902. }
  19903. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19904. get: function () {
  19905. return this._singleClick;
  19906. },
  19907. set: function (b) {
  19908. this._singleClick = b;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19914. get: function () {
  19915. return this._doubleClick;
  19916. },
  19917. set: function (b) {
  19918. this._doubleClick = b;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19924. get: function () {
  19925. return this._hasSwiped;
  19926. },
  19927. set: function (b) {
  19928. this._hasSwiped = b;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19934. get: function () {
  19935. return this._ignore;
  19936. },
  19937. set: function (b) {
  19938. this._ignore = b;
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. return ClickInfo;
  19944. }());
  19945. /**
  19946. * This class is used by the onRenderingGroupObservable
  19947. */
  19948. var RenderingGroupInfo = /** @class */ (function () {
  19949. function RenderingGroupInfo() {
  19950. }
  19951. /**
  19952. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19953. * This stage will be fired no matter what
  19954. */
  19955. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19956. /**
  19957. * Called before opaque object are rendered.
  19958. * This stage will be fired only if there's 3D Opaque content to render
  19959. */
  19960. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19961. /**
  19962. * Called after the opaque objects are rendered and before the transparent ones
  19963. * This stage will be fired only if there's 3D transparent content to render
  19964. */
  19965. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19966. /**
  19967. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19968. * This stage will be fired no matter what
  19969. */
  19970. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19971. return RenderingGroupInfo;
  19972. }());
  19973. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19974. /**
  19975. * Represents a scene to be rendered by the engine.
  19976. * @see http://doc.babylonjs.com/page.php?p=21911
  19977. */
  19978. var Scene = /** @class */ (function () {
  19979. /**
  19980. * @constructor
  19981. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19982. */
  19983. function Scene(engine) {
  19984. // Members
  19985. this.autoClear = true;
  19986. this.autoClearDepthAndStencil = true;
  19987. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19988. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19989. this.forceWireframe = false;
  19990. this._forcePointsCloud = false;
  19991. this.forceShowBoundingBoxes = false;
  19992. this.animationsEnabled = true;
  19993. this.useConstantAnimationDeltaTime = false;
  19994. this.constantlyUpdateMeshUnderPointer = false;
  19995. this.hoverCursor = "pointer";
  19996. this.defaultCursor = "";
  19997. /**
  19998. * This is used to call preventDefault() on pointer down
  19999. * in order to block unwanted artifacts like system double clicks
  20000. */
  20001. this.preventDefaultOnPointerDown = true;
  20002. // Metadata
  20003. this.metadata = null;
  20004. /**
  20005. * An event triggered when the scene is disposed.
  20006. * @type {BABYLON.Observable}
  20007. */
  20008. this.onDisposeObservable = new BABYLON.Observable();
  20009. /**
  20010. * An event triggered before rendering the scene (right after animations and physics)
  20011. * @type {BABYLON.Observable}
  20012. */
  20013. this.onBeforeRenderObservable = new BABYLON.Observable();
  20014. /**
  20015. * An event triggered after rendering the scene
  20016. * @type {BABYLON.Observable}
  20017. */
  20018. this.onAfterRenderObservable = new BABYLON.Observable();
  20019. /**
  20020. * An event triggered before animating the scene
  20021. * @type {BABYLON.Observable}
  20022. */
  20023. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20024. /**
  20025. * An event triggered after animations processing
  20026. * @type {BABYLON.Observable}
  20027. */
  20028. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20029. /**
  20030. * An event triggered before draw calls are ready to be sent
  20031. * @type {BABYLON.Observable}
  20032. */
  20033. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20034. /**
  20035. * An event triggered after draw calls have been sent
  20036. * @type {BABYLON.Observable}
  20037. */
  20038. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20039. /**
  20040. * An event triggered when physic simulation is about to be run
  20041. * @type {BABYLON.Observable}
  20042. */
  20043. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20044. /**
  20045. * An event triggered when physic simulation has been done
  20046. * @type {BABYLON.Observable}
  20047. */
  20048. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20049. /**
  20050. * An event triggered when the scene is ready
  20051. * @type {BABYLON.Observable}
  20052. */
  20053. this.onReadyObservable = new BABYLON.Observable();
  20054. /**
  20055. * An event triggered before rendering a camera
  20056. * @type {BABYLON.Observable}
  20057. */
  20058. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20059. /**
  20060. * An event triggered after rendering a camera
  20061. * @type {BABYLON.Observable}
  20062. */
  20063. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20064. /**
  20065. * An event triggered when active meshes evaluation is about to start
  20066. * @type {BABYLON.Observable}
  20067. */
  20068. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20069. /**
  20070. * An event triggered when active meshes evaluation is done
  20071. * @type {BABYLON.Observable}
  20072. */
  20073. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20074. /**
  20075. * An event triggered when particles rendering is about to start
  20076. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20077. * @type {BABYLON.Observable}
  20078. */
  20079. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20080. /**
  20081. * An event triggered when particles rendering is done
  20082. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20083. * @type {BABYLON.Observable}
  20084. */
  20085. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20086. /**
  20087. * An event triggered when sprites rendering is about to start
  20088. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20089. * @type {BABYLON.Observable}
  20090. */
  20091. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20092. /**
  20093. * An event triggered when sprites rendering is done
  20094. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20095. * @type {BABYLON.Observable}
  20096. */
  20097. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20098. /**
  20099. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20100. * @type {BABYLON.Observable}
  20101. */
  20102. this.onDataLoadedObservable = new BABYLON.Observable();
  20103. /**
  20104. * An event triggered when a camera is created
  20105. * @type {BABYLON.Observable}
  20106. */
  20107. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20108. /**
  20109. * An event triggered when a camera is removed
  20110. * @type {BABYLON.Observable}
  20111. */
  20112. this.onCameraRemovedObservable = new BABYLON.Observable();
  20113. /**
  20114. * An event triggered when a light is created
  20115. * @type {BABYLON.Observable}
  20116. */
  20117. this.onNewLightAddedObservable = new BABYLON.Observable();
  20118. /**
  20119. * An event triggered when a light is removed
  20120. * @type {BABYLON.Observable}
  20121. */
  20122. this.onLightRemovedObservable = new BABYLON.Observable();
  20123. /**
  20124. * An event triggered when a geometry is created
  20125. * @type {BABYLON.Observable}
  20126. */
  20127. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20128. /**
  20129. * An event triggered when a geometry is removed
  20130. * @type {BABYLON.Observable}
  20131. */
  20132. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20133. /**
  20134. * An event triggered when a transform node is created
  20135. * @type {BABYLON.Observable}
  20136. */
  20137. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20138. /**
  20139. * An event triggered when a transform node is removed
  20140. * @type {BABYLON.Observable}
  20141. */
  20142. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20143. /**
  20144. * An event triggered when a mesh is created
  20145. * @type {BABYLON.Observable}
  20146. */
  20147. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20148. /**
  20149. * An event triggered when a mesh is removed
  20150. * @type {BABYLON.Observable}
  20151. */
  20152. this.onMeshRemovedObservable = new BABYLON.Observable();
  20153. /**
  20154. * An event triggered when render targets are about to be rendered
  20155. * Can happen multiple times per frame.
  20156. * @type {BABYLON.Observable}
  20157. */
  20158. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20159. /**
  20160. * An event triggered when render targets were rendered.
  20161. * Can happen multiple times per frame.
  20162. * @type {BABYLON.Observable}
  20163. */
  20164. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20165. /**
  20166. * An event triggered before calculating deterministic simulation step
  20167. * @type {BABYLON.Observable}
  20168. */
  20169. this.onBeforeStepObservable = new BABYLON.Observable();
  20170. /**
  20171. * An event triggered after calculating deterministic simulation step
  20172. * @type {BABYLON.Observable}
  20173. */
  20174. this.onAfterStepObservable = new BABYLON.Observable();
  20175. /**
  20176. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20177. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20178. * 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)
  20179. */
  20180. this.onRenderingGroupObservable = new BABYLON.Observable();
  20181. // Animations
  20182. this.animations = [];
  20183. /**
  20184. * 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).
  20185. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20186. */
  20187. this.onPrePointerObservable = new BABYLON.Observable();
  20188. /**
  20189. * Observable event triggered each time an input event is received from the rendering canvas
  20190. */
  20191. this.onPointerObservable = new BABYLON.Observable();
  20192. this._meshPickProceed = false;
  20193. this._currentPickResult = null;
  20194. this._previousPickResult = null;
  20195. this._totalPointersPressed = 0;
  20196. this._doubleClickOccured = false;
  20197. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20198. this.cameraToUseForPointers = null;
  20199. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20200. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20201. this._startingPointerTime = 0;
  20202. this._previousStartingPointerTime = 0;
  20203. // Deterministic lockstep
  20204. this._timeAccumulator = 0;
  20205. this._currentStepId = 0;
  20206. this._currentInternalStep = 0;
  20207. // Keyboard
  20208. /**
  20209. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20210. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20211. */
  20212. this.onPreKeyboardObservable = new BABYLON.Observable();
  20213. /**
  20214. * Observable event triggered each time an keyboard event is received from the hosting window
  20215. */
  20216. this.onKeyboardObservable = new BABYLON.Observable();
  20217. // Coordinate system
  20218. /**
  20219. * use right-handed coordinate system on this scene.
  20220. * @type {boolean}
  20221. */
  20222. this._useRightHandedSystem = false;
  20223. // Fog
  20224. this._fogEnabled = true;
  20225. this._fogMode = Scene.FOGMODE_NONE;
  20226. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20227. this.fogDensity = 0.1;
  20228. this.fogStart = 0;
  20229. this.fogEnd = 1000.0;
  20230. // Lights
  20231. /**
  20232. * is shadow enabled on this scene.
  20233. * @type {boolean}
  20234. */
  20235. this._shadowsEnabled = true;
  20236. /**
  20237. * is light enabled on this scene.
  20238. * @type {boolean}
  20239. */
  20240. this._lightsEnabled = true;
  20241. /**
  20242. * All of the lights added to this scene.
  20243. * @see BABYLON.Light
  20244. * @type {BABYLON.Light[]}
  20245. */
  20246. this.lights = new Array();
  20247. // Cameras
  20248. /** All of the cameras added to this scene. */
  20249. this.cameras = new Array();
  20250. /** All of the active cameras added to this scene. */
  20251. this.activeCameras = new Array();
  20252. // Meshes
  20253. /**
  20254. * All of the tranform nodes added to this scene.
  20255. * @see BABYLON.TransformNode
  20256. * @type {BABYLON.TransformNode[]}
  20257. */
  20258. this.transformNodes = new Array();
  20259. /**
  20260. * All of the (abstract) meshes added to this scene.
  20261. * @see BABYLON.AbstractMesh
  20262. * @type {BABYLON.AbstractMesh[]}
  20263. */
  20264. this.meshes = new Array();
  20265. /**
  20266. * All of the animation groups added to this scene.
  20267. * @see BABYLON.AnimationGroup
  20268. * @type {BABYLON.AnimationGroup[]}
  20269. */
  20270. this.animationGroups = new Array();
  20271. // Geometries
  20272. this._geometries = new Array();
  20273. this.materials = new Array();
  20274. this.multiMaterials = new Array();
  20275. // Textures
  20276. this._texturesEnabled = true;
  20277. this.textures = new Array();
  20278. // Particles
  20279. this.particlesEnabled = true;
  20280. this.particleSystems = new Array();
  20281. // Sprites
  20282. this.spritesEnabled = true;
  20283. this.spriteManagers = new Array();
  20284. // Layers
  20285. this.layers = new Array();
  20286. this.highlightLayers = new Array();
  20287. // Skeletons
  20288. this._skeletonsEnabled = true;
  20289. this.skeletons = new Array();
  20290. // Morph targets
  20291. this.morphTargetManagers = new Array();
  20292. // Lens flares
  20293. this.lensFlaresEnabled = true;
  20294. this.lensFlareSystems = new Array();
  20295. // Collisions
  20296. this.collisionsEnabled = true;
  20297. /** Defines the gravity applied to this scene */
  20298. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20299. // Postprocesses
  20300. this.postProcesses = new Array();
  20301. this.postProcessesEnabled = true;
  20302. // Customs render targets
  20303. this.renderTargetsEnabled = true;
  20304. this.dumpNextRenderTargets = false;
  20305. this.customRenderTargets = new Array();
  20306. // Imported meshes
  20307. this.importedMeshesFiles = new Array();
  20308. // Probes
  20309. this.probesEnabled = true;
  20310. this.reflectionProbes = new Array();
  20311. this._actionManagers = new Array();
  20312. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20313. // Procedural textures
  20314. this.proceduralTexturesEnabled = true;
  20315. this._proceduralTextures = new Array();
  20316. this.soundTracks = new Array();
  20317. this._audioEnabled = true;
  20318. this._headphone = false;
  20319. // Performance counters
  20320. this._totalVertices = new BABYLON.PerfCounter();
  20321. this._activeIndices = new BABYLON.PerfCounter();
  20322. this._activeParticles = new BABYLON.PerfCounter();
  20323. this._activeBones = new BABYLON.PerfCounter();
  20324. this._animationTime = 0;
  20325. this.animationTimeScale = 1;
  20326. this._renderId = 0;
  20327. this._executeWhenReadyTimeoutId = -1;
  20328. this._intermediateRendering = false;
  20329. this._viewUpdateFlag = -1;
  20330. this._projectionUpdateFlag = -1;
  20331. this._alternateViewUpdateFlag = -1;
  20332. this._alternateProjectionUpdateFlag = -1;
  20333. this._toBeDisposed = new BABYLON.SmartArray(256);
  20334. this._activeRequests = new Array();
  20335. this._pendingData = new Array();
  20336. this._isDisposed = false;
  20337. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20338. this._activeMeshes = new BABYLON.SmartArray(256);
  20339. this._processedMaterials = new BABYLON.SmartArray(256);
  20340. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20341. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20342. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20343. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20344. this._activeAnimatables = new Array();
  20345. this._transformMatrix = BABYLON.Matrix.Zero();
  20346. this._useAlternateCameraConfiguration = false;
  20347. this._alternateRendering = false;
  20348. this.requireLightSorting = false;
  20349. this._activeMeshesFrozen = false;
  20350. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20351. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20352. this._engine.scenes.push(this);
  20353. this._uid = null;
  20354. this._renderingManager = new BABYLON.RenderingManager(this);
  20355. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20356. if (BABYLON.OutlineRenderer) {
  20357. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20358. }
  20359. if (BABYLON.Tools.IsWindowObjectExist()) {
  20360. this.attachControl();
  20361. }
  20362. //simplification queue
  20363. if (BABYLON.SimplificationQueue) {
  20364. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20365. }
  20366. //collision coordinator initialization. For now legacy per default.
  20367. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20368. // Uniform Buffer
  20369. this._createUbo();
  20370. // Default Image processing definition.
  20371. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20372. }
  20373. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20374. /** The fog is deactivated */
  20375. get: function () {
  20376. return Scene._FOGMODE_NONE;
  20377. },
  20378. enumerable: true,
  20379. configurable: true
  20380. });
  20381. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20382. /** The fog density is following an exponential function */
  20383. get: function () {
  20384. return Scene._FOGMODE_EXP;
  20385. },
  20386. enumerable: true,
  20387. configurable: true
  20388. });
  20389. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20390. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20391. get: function () {
  20392. return Scene._FOGMODE_EXP2;
  20393. },
  20394. enumerable: true,
  20395. configurable: true
  20396. });
  20397. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20398. /** The fog density is following a linear function. */
  20399. get: function () {
  20400. return Scene._FOGMODE_LINEAR;
  20401. },
  20402. enumerable: true,
  20403. configurable: true
  20404. });
  20405. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20406. /**
  20407. * Texture used in all pbr material as the reflection texture.
  20408. * As in the majority of the scene they are the same (exception for multi room and so on),
  20409. * this is easier to reference from here than from all the materials.
  20410. */
  20411. get: function () {
  20412. return this._environmentTexture;
  20413. },
  20414. /**
  20415. * Texture used in all pbr material as the reflection texture.
  20416. * As in the majority of the scene they are the same (exception for multi room and so on),
  20417. * this is easier to set here than in all the materials.
  20418. */
  20419. set: function (value) {
  20420. if (this._environmentTexture === value) {
  20421. return;
  20422. }
  20423. this._environmentTexture = value;
  20424. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20425. },
  20426. enumerable: true,
  20427. configurable: true
  20428. });
  20429. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20430. /**
  20431. * Default image processing configuration used either in the rendering
  20432. * Forward main pass or through the imageProcessingPostProcess if present.
  20433. * As in the majority of the scene they are the same (exception for multi camera),
  20434. * this is easier to reference from here than from all the materials and post process.
  20435. *
  20436. * No setter as we it is a shared configuration, you can set the values instead.
  20437. */
  20438. get: function () {
  20439. return this._imageProcessingConfiguration;
  20440. },
  20441. enumerable: true,
  20442. configurable: true
  20443. });
  20444. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20445. get: function () {
  20446. return this._forcePointsCloud;
  20447. },
  20448. set: function (value) {
  20449. if (this._forcePointsCloud === value) {
  20450. return;
  20451. }
  20452. this._forcePointsCloud = value;
  20453. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Object.defineProperty(Scene.prototype, "onDispose", {
  20459. /** A function to be executed when this scene is disposed. */
  20460. set: function (callback) {
  20461. if (this._onDisposeObserver) {
  20462. this.onDisposeObservable.remove(this._onDisposeObserver);
  20463. }
  20464. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20465. },
  20466. enumerable: true,
  20467. configurable: true
  20468. });
  20469. Object.defineProperty(Scene.prototype, "beforeRender", {
  20470. /** A function to be executed before rendering this scene */
  20471. set: function (callback) {
  20472. if (this._onBeforeRenderObserver) {
  20473. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20474. }
  20475. if (callback) {
  20476. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20477. }
  20478. },
  20479. enumerable: true,
  20480. configurable: true
  20481. });
  20482. Object.defineProperty(Scene.prototype, "afterRender", {
  20483. /** A function to be executed after rendering this scene */
  20484. set: function (callback) {
  20485. if (this._onAfterRenderObserver) {
  20486. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20487. }
  20488. if (callback) {
  20489. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20490. }
  20491. },
  20492. enumerable: true,
  20493. configurable: true
  20494. });
  20495. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20496. set: function (callback) {
  20497. if (this._onBeforeCameraRenderObserver) {
  20498. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20499. }
  20500. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20501. },
  20502. enumerable: true,
  20503. configurable: true
  20504. });
  20505. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20506. set: function (callback) {
  20507. if (this._onAfterCameraRenderObserver) {
  20508. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20509. }
  20510. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20511. },
  20512. enumerable: true,
  20513. configurable: true
  20514. });
  20515. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20516. get: function () {
  20517. if (!this._gamepadManager) {
  20518. this._gamepadManager = new BABYLON.GamepadManager(this);
  20519. }
  20520. return this._gamepadManager;
  20521. },
  20522. enumerable: true,
  20523. configurable: true
  20524. });
  20525. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20526. get: function () {
  20527. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20528. },
  20529. enumerable: true,
  20530. configurable: true
  20531. });
  20532. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20533. get: function () {
  20534. return this._useRightHandedSystem;
  20535. },
  20536. set: function (value) {
  20537. if (this._useRightHandedSystem === value) {
  20538. return;
  20539. }
  20540. this._useRightHandedSystem = value;
  20541. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Scene.prototype.setStepId = function (newStepId) {
  20547. this._currentStepId = newStepId;
  20548. };
  20549. ;
  20550. Scene.prototype.getStepId = function () {
  20551. return this._currentStepId;
  20552. };
  20553. ;
  20554. Scene.prototype.getInternalStep = function () {
  20555. return this._currentInternalStep;
  20556. };
  20557. ;
  20558. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20559. get: function () {
  20560. return this._fogEnabled;
  20561. },
  20562. /**
  20563. * is fog enabled on this scene.
  20564. */
  20565. set: function (value) {
  20566. if (this._fogEnabled === value) {
  20567. return;
  20568. }
  20569. this._fogEnabled = value;
  20570. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20571. },
  20572. enumerable: true,
  20573. configurable: true
  20574. });
  20575. Object.defineProperty(Scene.prototype, "fogMode", {
  20576. get: function () {
  20577. return this._fogMode;
  20578. },
  20579. set: function (value) {
  20580. if (this._fogMode === value) {
  20581. return;
  20582. }
  20583. this._fogMode = value;
  20584. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20585. },
  20586. enumerable: true,
  20587. configurable: true
  20588. });
  20589. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20590. get: function () {
  20591. return this._shadowsEnabled;
  20592. },
  20593. set: function (value) {
  20594. if (this._shadowsEnabled === value) {
  20595. return;
  20596. }
  20597. this._shadowsEnabled = value;
  20598. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20599. },
  20600. enumerable: true,
  20601. configurable: true
  20602. });
  20603. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20604. get: function () {
  20605. return this._lightsEnabled;
  20606. },
  20607. set: function (value) {
  20608. if (this._lightsEnabled === value) {
  20609. return;
  20610. }
  20611. this._lightsEnabled = value;
  20612. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20613. },
  20614. enumerable: true,
  20615. configurable: true
  20616. });
  20617. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20618. /** The default material used on meshes when no material is affected */
  20619. get: function () {
  20620. if (!this._defaultMaterial) {
  20621. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20622. }
  20623. return this._defaultMaterial;
  20624. },
  20625. /** The default material used on meshes when no material is affected */
  20626. set: function (value) {
  20627. this._defaultMaterial = value;
  20628. },
  20629. enumerable: true,
  20630. configurable: true
  20631. });
  20632. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20633. get: function () {
  20634. return this._texturesEnabled;
  20635. },
  20636. set: function (value) {
  20637. if (this._texturesEnabled === value) {
  20638. return;
  20639. }
  20640. this._texturesEnabled = value;
  20641. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20642. },
  20643. enumerable: true,
  20644. configurable: true
  20645. });
  20646. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20647. get: function () {
  20648. return this._skeletonsEnabled;
  20649. },
  20650. set: function (value) {
  20651. if (this._skeletonsEnabled === value) {
  20652. return;
  20653. }
  20654. this._skeletonsEnabled = value;
  20655. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20656. },
  20657. enumerable: true,
  20658. configurable: true
  20659. });
  20660. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20661. get: function () {
  20662. if (!this._postProcessRenderPipelineManager) {
  20663. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20664. }
  20665. return this._postProcessRenderPipelineManager;
  20666. },
  20667. enumerable: true,
  20668. configurable: true
  20669. });
  20670. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20671. get: function () {
  20672. if (!this._mainSoundTrack) {
  20673. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20674. }
  20675. return this._mainSoundTrack;
  20676. },
  20677. enumerable: true,
  20678. configurable: true
  20679. });
  20680. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20681. get: function () {
  20682. return this._alternateRendering;
  20683. },
  20684. enumerable: true,
  20685. configurable: true
  20686. });
  20687. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20688. get: function () {
  20689. return this._frustumPlanes;
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20695. /**
  20696. * Gets the current geometry buffer associated to the scene.
  20697. */
  20698. get: function () {
  20699. return this._geometryBufferRenderer;
  20700. },
  20701. /**
  20702. * Sets the current geometry buffer for the scene.
  20703. */
  20704. set: function (geometryBufferRenderer) {
  20705. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20706. this._geometryBufferRenderer = geometryBufferRenderer;
  20707. }
  20708. },
  20709. enumerable: true,
  20710. configurable: true
  20711. });
  20712. Object.defineProperty(Scene.prototype, "debugLayer", {
  20713. // Properties
  20714. get: function () {
  20715. if (!this._debugLayer) {
  20716. this._debugLayer = new BABYLON.DebugLayer(this);
  20717. }
  20718. return this._debugLayer;
  20719. },
  20720. enumerable: true,
  20721. configurable: true
  20722. });
  20723. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20724. get: function () {
  20725. return this._workerCollisions;
  20726. },
  20727. set: function (enabled) {
  20728. if (!BABYLON.CollisionCoordinatorLegacy) {
  20729. return;
  20730. }
  20731. enabled = (enabled && !!Worker);
  20732. this._workerCollisions = enabled;
  20733. if (this.collisionCoordinator) {
  20734. this.collisionCoordinator.destroy();
  20735. }
  20736. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20737. this.collisionCoordinator.init(this);
  20738. },
  20739. enumerable: true,
  20740. configurable: true
  20741. });
  20742. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20743. get: function () {
  20744. return this._selectionOctree;
  20745. },
  20746. enumerable: true,
  20747. configurable: true
  20748. });
  20749. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20750. /**
  20751. * The mesh that is currently under the pointer.
  20752. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20753. */
  20754. get: function () {
  20755. return this._pointerOverMesh;
  20756. },
  20757. enumerable: true,
  20758. configurable: true
  20759. });
  20760. Object.defineProperty(Scene.prototype, "pointerX", {
  20761. /**
  20762. * Current on-screen X position of the pointer
  20763. * @return {number} X position of the pointer
  20764. */
  20765. get: function () {
  20766. return this._pointerX;
  20767. },
  20768. enumerable: true,
  20769. configurable: true
  20770. });
  20771. Object.defineProperty(Scene.prototype, "pointerY", {
  20772. /**
  20773. * Current on-screen Y position of the pointer
  20774. * @return {number} Y position of the pointer
  20775. */
  20776. get: function () {
  20777. return this._pointerY;
  20778. },
  20779. enumerable: true,
  20780. configurable: true
  20781. });
  20782. Scene.prototype.getCachedMaterial = function () {
  20783. return this._cachedMaterial;
  20784. };
  20785. Scene.prototype.getCachedEffect = function () {
  20786. return this._cachedEffect;
  20787. };
  20788. Scene.prototype.getCachedVisibility = function () {
  20789. return this._cachedVisibility;
  20790. };
  20791. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20792. if (visibility === void 0) { visibility = 1; }
  20793. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20794. };
  20795. Scene.prototype.getBoundingBoxRenderer = function () {
  20796. if (!this._boundingBoxRenderer) {
  20797. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20798. }
  20799. return this._boundingBoxRenderer;
  20800. };
  20801. Scene.prototype.getOutlineRenderer = function () {
  20802. return this._outlineRenderer;
  20803. };
  20804. Scene.prototype.getEngine = function () {
  20805. return this._engine;
  20806. };
  20807. Scene.prototype.getTotalVertices = function () {
  20808. return this._totalVertices.current;
  20809. };
  20810. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20811. get: function () {
  20812. return this._totalVertices;
  20813. },
  20814. enumerable: true,
  20815. configurable: true
  20816. });
  20817. Scene.prototype.getActiveIndices = function () {
  20818. return this._activeIndices.current;
  20819. };
  20820. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20821. get: function () {
  20822. return this._activeIndices;
  20823. },
  20824. enumerable: true,
  20825. configurable: true
  20826. });
  20827. Scene.prototype.getActiveParticles = function () {
  20828. return this._activeParticles.current;
  20829. };
  20830. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20831. get: function () {
  20832. return this._activeParticles;
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. Scene.prototype.getActiveBones = function () {
  20838. return this._activeBones.current;
  20839. };
  20840. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20841. get: function () {
  20842. return this._activeBones;
  20843. },
  20844. enumerable: true,
  20845. configurable: true
  20846. });
  20847. // Stats
  20848. Scene.prototype.getInterFramePerfCounter = function () {
  20849. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20850. return 0;
  20851. };
  20852. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20853. get: function () {
  20854. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20855. return null;
  20856. },
  20857. enumerable: true,
  20858. configurable: true
  20859. });
  20860. Scene.prototype.getLastFrameDuration = function () {
  20861. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20862. return 0;
  20863. };
  20864. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20865. get: function () {
  20866. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20867. return null;
  20868. },
  20869. enumerable: true,
  20870. configurable: true
  20871. });
  20872. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20873. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20874. return 0;
  20875. };
  20876. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20877. get: function () {
  20878. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20879. return null;
  20880. },
  20881. enumerable: true,
  20882. configurable: true
  20883. });
  20884. Scene.prototype.getActiveMeshes = function () {
  20885. return this._activeMeshes;
  20886. };
  20887. Scene.prototype.getRenderTargetsDuration = function () {
  20888. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20889. return 0;
  20890. };
  20891. Scene.prototype.getRenderDuration = function () {
  20892. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20893. return 0;
  20894. };
  20895. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20896. get: function () {
  20897. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20898. return null;
  20899. },
  20900. enumerable: true,
  20901. configurable: true
  20902. });
  20903. Scene.prototype.getParticlesDuration = function () {
  20904. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20905. return 0;
  20906. };
  20907. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20908. get: function () {
  20909. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20910. return null;
  20911. },
  20912. enumerable: true,
  20913. configurable: true
  20914. });
  20915. Scene.prototype.getSpritesDuration = function () {
  20916. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20917. return 0;
  20918. };
  20919. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20920. get: function () {
  20921. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20922. return null;
  20923. },
  20924. enumerable: true,
  20925. configurable: true
  20926. });
  20927. Scene.prototype.getAnimationRatio = function () {
  20928. return this._animationRatio;
  20929. };
  20930. Scene.prototype.getRenderId = function () {
  20931. return this._renderId;
  20932. };
  20933. Scene.prototype.incrementRenderId = function () {
  20934. this._renderId++;
  20935. };
  20936. Scene.prototype._updatePointerPosition = function (evt) {
  20937. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20938. if (!canvasRect) {
  20939. return;
  20940. }
  20941. this._pointerX = evt.clientX - canvasRect.left;
  20942. this._pointerY = evt.clientY - canvasRect.top;
  20943. this._unTranslatedPointerX = this._pointerX;
  20944. this._unTranslatedPointerY = this._pointerY;
  20945. };
  20946. Scene.prototype._createUbo = function () {
  20947. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20948. this._sceneUbo.addUniform("viewProjection", 16);
  20949. this._sceneUbo.addUniform("view", 16);
  20950. };
  20951. Scene.prototype._createAlternateUbo = function () {
  20952. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20953. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20954. this._alternateSceneUbo.addUniform("view", 16);
  20955. };
  20956. // Pointers handling
  20957. /**
  20958. * Use this method to simulate a pointer move on a mesh
  20959. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20960. */
  20961. Scene.prototype.simulatePointerMove = function (pickResult) {
  20962. var evt = new PointerEvent("pointermove");
  20963. return this._processPointerMove(pickResult, evt);
  20964. };
  20965. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20966. var canvas = this._engine.getRenderingCanvas();
  20967. if (!canvas) {
  20968. return this;
  20969. }
  20970. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20971. this.setPointerOverSprite(null);
  20972. this.setPointerOverMesh(pickResult.pickedMesh);
  20973. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20974. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20975. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20976. }
  20977. else {
  20978. canvas.style.cursor = this.hoverCursor;
  20979. }
  20980. }
  20981. else {
  20982. canvas.style.cursor = this.defaultCursor;
  20983. }
  20984. }
  20985. else {
  20986. this.setPointerOverMesh(null);
  20987. // Sprites
  20988. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20989. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20990. this.setPointerOverSprite(pickResult.pickedSprite);
  20991. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20992. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20993. }
  20994. else {
  20995. canvas.style.cursor = this.hoverCursor;
  20996. }
  20997. }
  20998. else {
  20999. this.setPointerOverSprite(null);
  21000. // Restore pointer
  21001. canvas.style.cursor = this.defaultCursor;
  21002. }
  21003. }
  21004. if (pickResult) {
  21005. if (this.onPointerMove) {
  21006. this.onPointerMove(evt, pickResult);
  21007. }
  21008. if (this.onPointerObservable.hasObservers()) {
  21009. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21010. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21011. this.onPointerObservable.notifyObservers(pi, type);
  21012. }
  21013. }
  21014. return this;
  21015. };
  21016. /**
  21017. * Use this method to simulate a pointer down on a mesh
  21018. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21019. */
  21020. Scene.prototype.simulatePointerDown = function (pickResult) {
  21021. var evt = new PointerEvent("pointerdown");
  21022. return this._processPointerDown(pickResult, evt);
  21023. };
  21024. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21025. var _this = this;
  21026. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21027. this._pickedDownMesh = pickResult.pickedMesh;
  21028. var actionManager = pickResult.pickedMesh.actionManager;
  21029. if (actionManager) {
  21030. if (actionManager.hasPickTriggers) {
  21031. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21032. switch (evt.button) {
  21033. case 0:
  21034. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21035. break;
  21036. case 1:
  21037. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21038. break;
  21039. case 2:
  21040. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21041. break;
  21042. }
  21043. }
  21044. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21045. window.setTimeout(function () {
  21046. 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);
  21047. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21048. if (_this._totalPointersPressed !== 0 &&
  21049. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21050. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21051. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21052. _this._startingPointerTime = 0;
  21053. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21054. }
  21055. }
  21056. }, Scene.LongPressDelay);
  21057. }
  21058. }
  21059. }
  21060. if (pickResult) {
  21061. if (this.onPointerDown) {
  21062. this.onPointerDown(evt, pickResult);
  21063. }
  21064. if (this.onPointerObservable.hasObservers()) {
  21065. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21066. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21067. this.onPointerObservable.notifyObservers(pi, type);
  21068. }
  21069. }
  21070. return this;
  21071. };
  21072. /**
  21073. * Use this method to simulate a pointer up on a mesh
  21074. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21075. */
  21076. Scene.prototype.simulatePointerUp = function (pickResult) {
  21077. var evt = new PointerEvent("pointerup");
  21078. var clickInfo = new ClickInfo();
  21079. clickInfo.singleClick = true;
  21080. clickInfo.ignore = true;
  21081. return this._processPointerUp(pickResult, evt, clickInfo);
  21082. };
  21083. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21084. if (pickResult && pickResult && pickResult.pickedMesh) {
  21085. this._pickedUpMesh = pickResult.pickedMesh;
  21086. if (this._pickedDownMesh === this._pickedUpMesh) {
  21087. if (this.onPointerPick) {
  21088. this.onPointerPick(evt, pickResult);
  21089. }
  21090. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21091. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21092. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21093. this.onPointerObservable.notifyObservers(pi, type);
  21094. }
  21095. }
  21096. if (pickResult.pickedMesh.actionManager) {
  21097. if (clickInfo.ignore) {
  21098. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21099. }
  21100. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21101. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21102. }
  21103. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21104. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21105. }
  21106. }
  21107. }
  21108. if (this._pickedDownMesh &&
  21109. this._pickedDownMesh.actionManager &&
  21110. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21111. this._pickedDownMesh !== this._pickedUpMesh) {
  21112. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21113. }
  21114. if (this.onPointerUp) {
  21115. this.onPointerUp(evt, pickResult);
  21116. }
  21117. if (this.onPointerObservable.hasObservers()) {
  21118. if (!clickInfo.ignore) {
  21119. if (!clickInfo.hasSwiped) {
  21120. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21121. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21122. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21123. this.onPointerObservable.notifyObservers(pi, type);
  21124. }
  21125. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21126. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21127. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21128. this.onPointerObservable.notifyObservers(pi, type);
  21129. }
  21130. }
  21131. }
  21132. else {
  21133. var type = BABYLON.PointerEventTypes.POINTERUP;
  21134. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21135. this.onPointerObservable.notifyObservers(pi, type);
  21136. }
  21137. }
  21138. return this;
  21139. };
  21140. /**
  21141. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21142. * @param attachUp defines if you want to attach events to pointerup
  21143. * @param attachDown defines if you want to attach events to pointerdown
  21144. * @param attachMove defines if you want to attach events to pointermove
  21145. */
  21146. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21147. var _this = this;
  21148. if (attachUp === void 0) { attachUp = true; }
  21149. if (attachDown === void 0) { attachDown = true; }
  21150. if (attachMove === void 0) { attachMove = true; }
  21151. this._initActionManager = function (act, clickInfo) {
  21152. if (!_this._meshPickProceed) {
  21153. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21154. _this._currentPickResult = pickResult;
  21155. if (pickResult) {
  21156. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21157. }
  21158. _this._meshPickProceed = true;
  21159. }
  21160. return act;
  21161. };
  21162. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21163. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21164. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21165. btn !== _this._previousButtonPressed) {
  21166. _this._doubleClickOccured = false;
  21167. clickInfo.singleClick = true;
  21168. clickInfo.ignore = false;
  21169. cb(clickInfo, _this._currentPickResult);
  21170. }
  21171. };
  21172. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21173. var clickInfo = new ClickInfo();
  21174. _this._currentPickResult = null;
  21175. var act = null;
  21176. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21177. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21178. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21179. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21180. act = _this._initActionManager(act, clickInfo);
  21181. if (act)
  21182. checkPicking = act.hasPickTriggers;
  21183. }
  21184. if (checkPicking) {
  21185. var btn = evt.button;
  21186. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21187. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21188. if (!clickInfo.hasSwiped) {
  21189. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21190. if (!checkSingleClickImmediately) {
  21191. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21192. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21193. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21194. act = _this._initActionManager(act, clickInfo);
  21195. if (act)
  21196. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21197. }
  21198. }
  21199. if (checkSingleClickImmediately) {
  21200. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21201. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21202. btn !== _this._previousButtonPressed) {
  21203. clickInfo.singleClick = true;
  21204. cb(clickInfo, _this._currentPickResult);
  21205. }
  21206. }
  21207. else {
  21208. // wait that no double click has been raised during the double click delay
  21209. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21210. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21211. }
  21212. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21213. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21214. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21215. act = _this._initActionManager(act, clickInfo);
  21216. if (act)
  21217. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21218. }
  21219. if (checkDoubleClick) {
  21220. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21221. if (btn === _this._previousButtonPressed &&
  21222. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21223. !_this._doubleClickOccured) {
  21224. // pointer has not moved for 2 clicks, it's a double click
  21225. if (!clickInfo.hasSwiped &&
  21226. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21227. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21228. _this._previousStartingPointerTime = 0;
  21229. _this._doubleClickOccured = true;
  21230. clickInfo.doubleClick = true;
  21231. clickInfo.ignore = false;
  21232. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21233. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21234. }
  21235. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21236. cb(clickInfo, _this._currentPickResult);
  21237. }
  21238. else {
  21239. _this._doubleClickOccured = false;
  21240. _this._previousStartingPointerTime = _this._startingPointerTime;
  21241. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21242. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21243. _this._previousButtonPressed = btn;
  21244. if (Scene.ExclusiveDoubleClickMode) {
  21245. if (_this._previousDelayedSimpleClickTimeout) {
  21246. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21247. }
  21248. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21249. cb(clickInfo, _this._previousPickResult);
  21250. }
  21251. else {
  21252. cb(clickInfo, _this._currentPickResult);
  21253. }
  21254. }
  21255. }
  21256. else {
  21257. _this._doubleClickOccured = false;
  21258. _this._previousStartingPointerTime = _this._startingPointerTime;
  21259. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21260. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21261. _this._previousButtonPressed = btn;
  21262. }
  21263. }
  21264. }
  21265. }
  21266. clickInfo.ignore = true;
  21267. cb(clickInfo, _this._currentPickResult);
  21268. };
  21269. this._spritePredicate = function (sprite) {
  21270. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21271. };
  21272. this._onPointerMove = function (evt) {
  21273. _this._updatePointerPosition(evt);
  21274. // PreObservable support
  21275. if (_this.onPrePointerObservable.hasObservers()) {
  21276. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21277. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21278. _this.onPrePointerObservable.notifyObservers(pi, type);
  21279. if (pi.skipOnPointerObservable) {
  21280. return;
  21281. }
  21282. }
  21283. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21284. return;
  21285. }
  21286. if (!_this.pointerMovePredicate) {
  21287. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21288. }
  21289. // Meshes
  21290. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21291. _this._processPointerMove(pickResult, evt);
  21292. };
  21293. this._onPointerDown = function (evt) {
  21294. _this._totalPointersPressed++;
  21295. _this._pickedDownMesh = null;
  21296. _this._meshPickProceed = false;
  21297. _this._updatePointerPosition(evt);
  21298. if (_this.preventDefaultOnPointerDown && canvas) {
  21299. evt.preventDefault();
  21300. canvas.focus();
  21301. }
  21302. // PreObservable support
  21303. if (_this.onPrePointerObservable.hasObservers()) {
  21304. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21305. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21306. _this.onPrePointerObservable.notifyObservers(pi, type);
  21307. if (pi.skipOnPointerObservable) {
  21308. return;
  21309. }
  21310. }
  21311. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21312. return;
  21313. }
  21314. _this._startingPointerPosition.x = _this._pointerX;
  21315. _this._startingPointerPosition.y = _this._pointerY;
  21316. _this._startingPointerTime = new Date().getTime();
  21317. if (!_this.pointerDownPredicate) {
  21318. _this.pointerDownPredicate = function (mesh) {
  21319. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21320. };
  21321. }
  21322. // Meshes
  21323. _this._pickedDownMesh = null;
  21324. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21325. _this._processPointerDown(pickResult, evt);
  21326. // Sprites
  21327. _this._pickedDownSprite = null;
  21328. if (_this.spriteManagers.length > 0) {
  21329. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21330. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21331. if (pickResult.pickedSprite.actionManager) {
  21332. _this._pickedDownSprite = pickResult.pickedSprite;
  21333. switch (evt.button) {
  21334. case 0:
  21335. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21336. break;
  21337. case 1:
  21338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21339. break;
  21340. case 2:
  21341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21342. break;
  21343. }
  21344. if (pickResult.pickedSprite.actionManager) {
  21345. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21346. }
  21347. }
  21348. }
  21349. }
  21350. };
  21351. this._onPointerUp = function (evt) {
  21352. if (_this._totalPointersPressed === 0) {
  21353. return; // So we need to test it the pointer down was pressed before.
  21354. }
  21355. _this._totalPointersPressed--;
  21356. _this._pickedUpMesh = null;
  21357. _this._meshPickProceed = false;
  21358. _this._updatePointerPosition(evt);
  21359. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21360. // PreObservable support
  21361. if (_this.onPrePointerObservable.hasObservers()) {
  21362. if (!clickInfo.ignore) {
  21363. if (!clickInfo.hasSwiped) {
  21364. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21365. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21366. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21367. _this.onPrePointerObservable.notifyObservers(pi, type);
  21368. if (pi.skipOnPointerObservable) {
  21369. return;
  21370. }
  21371. }
  21372. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21373. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21374. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21375. _this.onPrePointerObservable.notifyObservers(pi, type);
  21376. if (pi.skipOnPointerObservable) {
  21377. return;
  21378. }
  21379. }
  21380. }
  21381. }
  21382. else {
  21383. var type = BABYLON.PointerEventTypes.POINTERUP;
  21384. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21385. _this.onPrePointerObservable.notifyObservers(pi, type);
  21386. if (pi.skipOnPointerObservable) {
  21387. return;
  21388. }
  21389. }
  21390. }
  21391. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21392. return;
  21393. }
  21394. if (!_this.pointerUpPredicate) {
  21395. _this.pointerUpPredicate = function (mesh) {
  21396. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21397. };
  21398. }
  21399. // Meshes
  21400. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21401. _this._initActionManager(null, clickInfo);
  21402. }
  21403. if (!pickResult) {
  21404. pickResult = _this._currentPickResult;
  21405. }
  21406. _this._processPointerUp(pickResult, evt, clickInfo);
  21407. // Sprites
  21408. if (_this.spriteManagers.length > 0) {
  21409. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21410. if (spritePickResult) {
  21411. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21412. if (spritePickResult.pickedSprite.actionManager) {
  21413. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21414. if (spritePickResult.pickedSprite.actionManager) {
  21415. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21416. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21417. }
  21418. }
  21419. }
  21420. }
  21421. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21422. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21423. }
  21424. }
  21425. }
  21426. _this._previousPickResult = _this._currentPickResult;
  21427. });
  21428. };
  21429. this._onKeyDown = function (evt) {
  21430. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21431. if (_this.onPreKeyboardObservable.hasObservers()) {
  21432. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21433. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21434. if (pi.skipOnPointerObservable) {
  21435. return;
  21436. }
  21437. }
  21438. if (_this.onKeyboardObservable.hasObservers()) {
  21439. var pi = new BABYLON.KeyboardInfo(type, evt);
  21440. _this.onKeyboardObservable.notifyObservers(pi, type);
  21441. }
  21442. if (_this.actionManager) {
  21443. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21444. }
  21445. };
  21446. this._onKeyUp = function (evt) {
  21447. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21448. if (_this.onPreKeyboardObservable.hasObservers()) {
  21449. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21450. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21451. if (pi.skipOnPointerObservable) {
  21452. return;
  21453. }
  21454. }
  21455. if (_this.onKeyboardObservable.hasObservers()) {
  21456. var pi = new BABYLON.KeyboardInfo(type, evt);
  21457. _this.onKeyboardObservable.notifyObservers(pi, type);
  21458. }
  21459. if (_this.actionManager) {
  21460. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21461. }
  21462. };
  21463. var engine = this.getEngine();
  21464. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21465. if (!canvas) {
  21466. return;
  21467. }
  21468. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21469. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21470. });
  21471. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21472. if (!canvas) {
  21473. return;
  21474. }
  21475. canvas.removeEventListener("keydown", _this._onKeyDown);
  21476. canvas.removeEventListener("keyup", _this._onKeyUp);
  21477. });
  21478. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21479. var canvas = this._engine.getRenderingCanvas();
  21480. if (!canvas) {
  21481. return;
  21482. }
  21483. if (attachMove) {
  21484. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21485. // Wheel
  21486. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21487. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21488. }
  21489. if (attachDown) {
  21490. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21491. }
  21492. if (attachUp) {
  21493. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21494. }
  21495. canvas.tabIndex = 1;
  21496. };
  21497. Scene.prototype.detachControl = function () {
  21498. var engine = this.getEngine();
  21499. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21500. var canvas = engine.getRenderingCanvas();
  21501. if (!canvas) {
  21502. return;
  21503. }
  21504. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21505. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21506. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21507. if (this._onCanvasBlurObserver) {
  21508. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21509. }
  21510. if (this._onCanvasFocusObserver) {
  21511. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21512. }
  21513. // Wheel
  21514. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21515. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21516. // Keyboard
  21517. canvas.removeEventListener("keydown", this._onKeyDown);
  21518. canvas.removeEventListener("keyup", this._onKeyUp);
  21519. // Observables
  21520. this.onKeyboardObservable.clear();
  21521. this.onPreKeyboardObservable.clear();
  21522. this.onPointerObservable.clear();
  21523. this.onPrePointerObservable.clear();
  21524. };
  21525. /**
  21526. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21527. * Delay loaded resources are not taking in account
  21528. * @return true if all required resources are ready
  21529. */
  21530. Scene.prototype.isReady = function () {
  21531. if (this._isDisposed) {
  21532. return false;
  21533. }
  21534. if (this._pendingData.length > 0) {
  21535. return false;
  21536. }
  21537. var index;
  21538. var engine = this.getEngine();
  21539. // Geometries
  21540. for (index = 0; index < this._geometries.length; index++) {
  21541. var geometry = this._geometries[index];
  21542. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21543. return false;
  21544. }
  21545. }
  21546. // Meshes
  21547. for (index = 0; index < this.meshes.length; index++) {
  21548. var mesh = this.meshes[index];
  21549. if (!mesh.isEnabled()) {
  21550. continue;
  21551. }
  21552. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21553. continue;
  21554. }
  21555. if (!mesh.isReady()) {
  21556. return false;
  21557. }
  21558. // Highlight layers
  21559. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21560. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21561. var layer = _a[_i];
  21562. if (!layer.hasMesh(mesh)) {
  21563. continue;
  21564. }
  21565. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21566. var subMesh = _c[_b];
  21567. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21568. return false;
  21569. }
  21570. }
  21571. }
  21572. }
  21573. return true;
  21574. };
  21575. Scene.prototype.resetCachedMaterial = function () {
  21576. this._cachedMaterial = null;
  21577. this._cachedEffect = null;
  21578. this._cachedVisibility = null;
  21579. };
  21580. Scene.prototype.registerBeforeRender = function (func) {
  21581. this.onBeforeRenderObservable.add(func);
  21582. };
  21583. Scene.prototype.unregisterBeforeRender = function (func) {
  21584. this.onBeforeRenderObservable.removeCallback(func);
  21585. };
  21586. Scene.prototype.registerAfterRender = function (func) {
  21587. this.onAfterRenderObservable.add(func);
  21588. };
  21589. Scene.prototype.unregisterAfterRender = function (func) {
  21590. this.onAfterRenderObservable.removeCallback(func);
  21591. };
  21592. Scene.prototype._executeOnceBeforeRender = function (func) {
  21593. var _this = this;
  21594. var execFunc = function () {
  21595. func();
  21596. setTimeout(function () {
  21597. _this.unregisterBeforeRender(execFunc);
  21598. });
  21599. };
  21600. this.registerBeforeRender(execFunc);
  21601. };
  21602. /**
  21603. * The provided function will run before render once and will be disposed afterwards.
  21604. * A timeout delay can be provided so that the function will be executed in N ms.
  21605. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21606. * @param func The function to be executed.
  21607. * @param timeout optional delay in ms
  21608. */
  21609. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21610. var _this = this;
  21611. if (timeout !== undefined) {
  21612. setTimeout(function () {
  21613. _this._executeOnceBeforeRender(func);
  21614. }, timeout);
  21615. }
  21616. else {
  21617. this._executeOnceBeforeRender(func);
  21618. }
  21619. };
  21620. Scene.prototype._addPendingData = function (data) {
  21621. this._pendingData.push(data);
  21622. };
  21623. Scene.prototype._removePendingData = function (data) {
  21624. var wasLoading = this.isLoading;
  21625. var index = this._pendingData.indexOf(data);
  21626. if (index !== -1) {
  21627. this._pendingData.splice(index, 1);
  21628. }
  21629. if (wasLoading && !this.isLoading) {
  21630. this.onDataLoadedObservable.notifyObservers(this);
  21631. }
  21632. };
  21633. Scene.prototype.getWaitingItemsCount = function () {
  21634. return this._pendingData.length;
  21635. };
  21636. Object.defineProperty(Scene.prototype, "isLoading", {
  21637. get: function () {
  21638. return this._pendingData.length > 0;
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. /**
  21644. * Registers a function to be executed when the scene is ready.
  21645. * @param {Function} func - the function to be executed.
  21646. */
  21647. Scene.prototype.executeWhenReady = function (func) {
  21648. var _this = this;
  21649. this.onReadyObservable.add(func);
  21650. if (this._executeWhenReadyTimeoutId !== -1) {
  21651. return;
  21652. }
  21653. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21654. _this._checkIsReady();
  21655. }, 150);
  21656. };
  21657. Scene.prototype._checkIsReady = function () {
  21658. var _this = this;
  21659. if (this.isReady()) {
  21660. this.onReadyObservable.notifyObservers(this);
  21661. this.onReadyObservable.clear();
  21662. this._executeWhenReadyTimeoutId = -1;
  21663. return;
  21664. }
  21665. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21666. _this._checkIsReady();
  21667. }, 150);
  21668. };
  21669. // Animations
  21670. /**
  21671. * Will start the animation sequence of a given target
  21672. * @param target - the target
  21673. * @param {number} from - from which frame should animation start
  21674. * @param {number} to - till which frame should animation run.
  21675. * @param {boolean} [loop] - should the animation loop
  21676. * @param {number} [speedRatio] - the speed in which to run the animation
  21677. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21678. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21679. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21680. * See BABYLON.Animatable
  21681. */
  21682. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21683. if (speedRatio === void 0) { speedRatio = 1.0; }
  21684. if (from > to && speedRatio > 0) {
  21685. speedRatio *= -1;
  21686. }
  21687. this.stopAnimation(target);
  21688. if (!animatable) {
  21689. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21690. }
  21691. // Local animations
  21692. if (target.animations) {
  21693. animatable.appendAnimations(target, target.animations);
  21694. }
  21695. // Children animations
  21696. if (target.getAnimatables) {
  21697. var animatables = target.getAnimatables();
  21698. for (var index = 0; index < animatables.length; index++) {
  21699. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21700. }
  21701. }
  21702. animatable.reset();
  21703. return animatable;
  21704. };
  21705. /**
  21706. * Begin a new animation on a given node
  21707. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21708. * @param {BABYLON.Animation[]} defines the list of animations to start
  21709. * @param {number} from defines the initial value
  21710. * @param {number} to defines the final value
  21711. * @param {boolean} loop defines if you want animation to loop (off by default)
  21712. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21713. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21714. * @returns the list of created animatables
  21715. */
  21716. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21717. if (speedRatio === undefined) {
  21718. speedRatio = 1.0;
  21719. }
  21720. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21721. return animatable;
  21722. };
  21723. /**
  21724. * Begin a new animation on a given node and its hierarchy
  21725. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21726. * @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.
  21727. * @param {BABYLON.Animation[]} defines the list of animations to start
  21728. * @param {number} from defines the initial value
  21729. * @param {number} to defines the final value
  21730. * @param {boolean} loop defines if you want animation to loop (off by default)
  21731. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21732. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21733. * @returns the list of animatables created for all nodes
  21734. */
  21735. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21736. var children = target.getDescendants(directDescendantsOnly);
  21737. var result = [];
  21738. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21739. var child = children_1[_i];
  21740. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21741. }
  21742. return result;
  21743. };
  21744. Scene.prototype.getAnimatableByTarget = function (target) {
  21745. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21746. if (this._activeAnimatables[index].target === target) {
  21747. return this._activeAnimatables[index];
  21748. }
  21749. }
  21750. return null;
  21751. };
  21752. Object.defineProperty(Scene.prototype, "animatables", {
  21753. get: function () {
  21754. return this._activeAnimatables;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. /**
  21760. * Will stop the animation of the given target
  21761. * @param target - the target
  21762. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21763. * @see beginAnimation
  21764. */
  21765. Scene.prototype.stopAnimation = function (target, animationName) {
  21766. var animatable = this.getAnimatableByTarget(target);
  21767. if (animatable) {
  21768. animatable.stop(animationName);
  21769. }
  21770. };
  21771. /**
  21772. * Stops and removes all animations that have been applied to the scene
  21773. */
  21774. Scene.prototype.stopAllAnimations = function () {
  21775. if (this._activeAnimatables) {
  21776. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21777. this._activeAnimatables[i].stop();
  21778. }
  21779. this._activeAnimatables = [];
  21780. }
  21781. };
  21782. Scene.prototype._animate = function () {
  21783. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21784. return;
  21785. }
  21786. // Getting time
  21787. var now = BABYLON.Tools.Now;
  21788. if (!this._animationTimeLast) {
  21789. if (this._pendingData.length > 0) {
  21790. return;
  21791. }
  21792. this._animationTimeLast = now;
  21793. }
  21794. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21795. this._animationTime += deltaTime;
  21796. this._animationTimeLast = now;
  21797. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21798. this._activeAnimatables[index]._animate(this._animationTime);
  21799. }
  21800. };
  21801. // Matrix
  21802. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21803. this._useAlternateCameraConfiguration = active;
  21804. };
  21805. Scene.prototype.getViewMatrix = function () {
  21806. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21807. };
  21808. Scene.prototype.getProjectionMatrix = function () {
  21809. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21810. };
  21811. Scene.prototype.getTransformMatrix = function () {
  21812. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21813. };
  21814. Scene.prototype.setTransformMatrix = function (view, projection) {
  21815. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21816. return;
  21817. }
  21818. this._viewUpdateFlag = view.updateFlag;
  21819. this._projectionUpdateFlag = projection.updateFlag;
  21820. this._viewMatrix = view;
  21821. this._projectionMatrix = projection;
  21822. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21823. // Update frustum
  21824. if (!this._frustumPlanes) {
  21825. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21826. }
  21827. else {
  21828. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21829. }
  21830. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21831. var otherCamera = this.activeCamera._alternateCamera;
  21832. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21833. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21834. }
  21835. if (this._sceneUbo.useUbo) {
  21836. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21837. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21838. this._sceneUbo.update();
  21839. }
  21840. };
  21841. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21842. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21843. return;
  21844. }
  21845. this._alternateViewUpdateFlag = view.updateFlag;
  21846. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21847. this._alternateViewMatrix = view;
  21848. this._alternateProjectionMatrix = projection;
  21849. if (!this._alternateTransformMatrix) {
  21850. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21851. }
  21852. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21853. if (!this._alternateSceneUbo) {
  21854. this._createAlternateUbo();
  21855. }
  21856. if (this._alternateSceneUbo.useUbo) {
  21857. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21858. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21859. this._alternateSceneUbo.update();
  21860. }
  21861. };
  21862. Scene.prototype.getSceneUniformBuffer = function () {
  21863. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21864. };
  21865. // Methods
  21866. Scene.prototype.getUniqueId = function () {
  21867. var result = Scene._uniqueIdCounter;
  21868. Scene._uniqueIdCounter++;
  21869. return result;
  21870. };
  21871. Scene.prototype.addMesh = function (newMesh) {
  21872. this.meshes.push(newMesh);
  21873. //notify the collision coordinator
  21874. if (this.collisionCoordinator) {
  21875. this.collisionCoordinator.onMeshAdded(newMesh);
  21876. }
  21877. newMesh._resyncLightSources();
  21878. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21879. };
  21880. Scene.prototype.removeMesh = function (toRemove) {
  21881. var index = this.meshes.indexOf(toRemove);
  21882. if (index !== -1) {
  21883. // Remove from the scene if mesh found
  21884. this.meshes.splice(index, 1);
  21885. }
  21886. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21887. return index;
  21888. };
  21889. Scene.prototype.addTransformNode = function (newTransformNode) {
  21890. this.transformNodes.push(newTransformNode);
  21891. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21892. };
  21893. Scene.prototype.removeTransformNode = function (toRemove) {
  21894. var index = this.transformNodes.indexOf(toRemove);
  21895. if (index !== -1) {
  21896. // Remove from the scene if found
  21897. this.transformNodes.splice(index, 1);
  21898. }
  21899. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21900. return index;
  21901. };
  21902. Scene.prototype.removeSkeleton = function (toRemove) {
  21903. var index = this.skeletons.indexOf(toRemove);
  21904. if (index !== -1) {
  21905. // Remove from the scene if found
  21906. this.skeletons.splice(index, 1);
  21907. }
  21908. return index;
  21909. };
  21910. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21911. var index = this.morphTargetManagers.indexOf(toRemove);
  21912. if (index !== -1) {
  21913. // Remove from the scene if found
  21914. this.morphTargetManagers.splice(index, 1);
  21915. }
  21916. return index;
  21917. };
  21918. Scene.prototype.removeLight = function (toRemove) {
  21919. var index = this.lights.indexOf(toRemove);
  21920. if (index !== -1) {
  21921. // Remove from meshes
  21922. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21923. var mesh = _a[_i];
  21924. mesh._removeLightSource(toRemove);
  21925. }
  21926. // Remove from the scene if mesh found
  21927. this.lights.splice(index, 1);
  21928. this.sortLightsByPriority();
  21929. }
  21930. this.onLightRemovedObservable.notifyObservers(toRemove);
  21931. return index;
  21932. };
  21933. Scene.prototype.removeCamera = function (toRemove) {
  21934. var index = this.cameras.indexOf(toRemove);
  21935. if (index !== -1) {
  21936. // Remove from the scene if mesh found
  21937. this.cameras.splice(index, 1);
  21938. }
  21939. // Remove from activeCameras
  21940. var index2 = this.activeCameras.indexOf(toRemove);
  21941. if (index2 !== -1) {
  21942. // Remove from the scene if mesh found
  21943. this.activeCameras.splice(index2, 1);
  21944. }
  21945. // Reset the activeCamera
  21946. if (this.activeCamera === toRemove) {
  21947. if (this.cameras.length > 0) {
  21948. this.activeCamera = this.cameras[0];
  21949. }
  21950. else {
  21951. this.activeCamera = null;
  21952. }
  21953. }
  21954. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21955. return index;
  21956. };
  21957. Scene.prototype.removeParticleSystem = function (toRemove) {
  21958. var index = this.particleSystems.indexOf(toRemove);
  21959. if (index !== -1) {
  21960. this.particleSystems.splice(index, 1);
  21961. }
  21962. return index;
  21963. };
  21964. ;
  21965. Scene.prototype.removeAnimation = function (toRemove) {
  21966. var index = this.animations.indexOf(toRemove);
  21967. if (index !== -1) {
  21968. this.animations.splice(index, 1);
  21969. }
  21970. return index;
  21971. };
  21972. ;
  21973. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21974. var index = this.multiMaterials.indexOf(toRemove);
  21975. if (index !== -1) {
  21976. this.multiMaterials.splice(index, 1);
  21977. }
  21978. return index;
  21979. };
  21980. ;
  21981. Scene.prototype.removeMaterial = function (toRemove) {
  21982. var index = this.materials.indexOf(toRemove);
  21983. if (index !== -1) {
  21984. this.materials.splice(index, 1);
  21985. }
  21986. return index;
  21987. };
  21988. ;
  21989. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21990. var index = this.lensFlareSystems.indexOf(toRemove);
  21991. if (index !== -1) {
  21992. this.lensFlareSystems.splice(index, 1);
  21993. }
  21994. return index;
  21995. };
  21996. ;
  21997. Scene.prototype.removeActionManager = function (toRemove) {
  21998. var index = this._actionManagers.indexOf(toRemove);
  21999. if (index !== -1) {
  22000. this._actionManagers.splice(index, 1);
  22001. }
  22002. return index;
  22003. };
  22004. ;
  22005. Scene.prototype.addLight = function (newLight) {
  22006. this.lights.push(newLight);
  22007. this.sortLightsByPriority();
  22008. // Add light to all meshes (To support if the light is removed and then readded)
  22009. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22010. var mesh = _a[_i];
  22011. if (mesh._lightSources.indexOf(newLight) === -1) {
  22012. mesh._lightSources.push(newLight);
  22013. mesh._resyncLightSources();
  22014. }
  22015. }
  22016. this.onNewLightAddedObservable.notifyObservers(newLight);
  22017. };
  22018. Scene.prototype.sortLightsByPriority = function () {
  22019. if (this.requireLightSorting) {
  22020. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22021. }
  22022. };
  22023. Scene.prototype.addCamera = function (newCamera) {
  22024. this.cameras.push(newCamera);
  22025. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22026. };
  22027. Scene.prototype.addSkeleton = function (newSkeleton) {
  22028. this.skeletons.push(newSkeleton);
  22029. };
  22030. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22031. this.particleSystems.push(newParticleSystem);
  22032. };
  22033. Scene.prototype.addAnimation = function (newAnimation) {
  22034. this.animations.push(newAnimation);
  22035. };
  22036. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22037. this.multiMaterials.push(newMultiMaterial);
  22038. };
  22039. Scene.prototype.addMaterial = function (newMaterial) {
  22040. this.materials.push(newMaterial);
  22041. };
  22042. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22043. this.morphTargetManagers.push(newMorphTargetManager);
  22044. };
  22045. Scene.prototype.addGeometry = function (newGeometrie) {
  22046. this._geometries.push(newGeometrie);
  22047. };
  22048. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22049. this.lensFlareSystems.push(newLensFlareSystem);
  22050. };
  22051. Scene.prototype.addActionManager = function (newActionManager) {
  22052. this._actionManagers.push(newActionManager);
  22053. };
  22054. /**
  22055. * Switch active camera
  22056. * @param {Camera} newCamera - new active camera
  22057. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22058. */
  22059. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22060. if (attachControl === void 0) { attachControl = true; }
  22061. var canvas = this._engine.getRenderingCanvas();
  22062. if (!canvas) {
  22063. return;
  22064. }
  22065. if (this.activeCamera) {
  22066. this.activeCamera.detachControl(canvas);
  22067. }
  22068. this.activeCamera = newCamera;
  22069. if (attachControl) {
  22070. newCamera.attachControl(canvas);
  22071. }
  22072. };
  22073. /**
  22074. * sets the active camera of the scene using its ID
  22075. * @param {string} id - the camera's ID
  22076. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22077. * @see activeCamera
  22078. */
  22079. Scene.prototype.setActiveCameraByID = function (id) {
  22080. var camera = this.getCameraByID(id);
  22081. if (camera) {
  22082. this.activeCamera = camera;
  22083. return camera;
  22084. }
  22085. return null;
  22086. };
  22087. /**
  22088. * sets the active camera of the scene using its name
  22089. * @param {string} name - the camera's name
  22090. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22091. * @see activeCamera
  22092. */
  22093. Scene.prototype.setActiveCameraByName = function (name) {
  22094. var camera = this.getCameraByName(name);
  22095. if (camera) {
  22096. this.activeCamera = camera;
  22097. return camera;
  22098. }
  22099. return null;
  22100. };
  22101. /**
  22102. * get an animation group using its name
  22103. * @param {string} the material's name
  22104. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22105. */
  22106. Scene.prototype.getAnimationGroupByName = function (name) {
  22107. for (var index = 0; index < this.animationGroups.length; index++) {
  22108. if (this.animationGroups[index].name === name) {
  22109. return this.animationGroups[index];
  22110. }
  22111. }
  22112. return null;
  22113. };
  22114. /**
  22115. * get a material using its id
  22116. * @param {string} the material's ID
  22117. * @return {BABYLON.Material|null} the material or null if none found.
  22118. */
  22119. Scene.prototype.getMaterialByID = function (id) {
  22120. for (var index = 0; index < this.materials.length; index++) {
  22121. if (this.materials[index].id === id) {
  22122. return this.materials[index];
  22123. }
  22124. }
  22125. return null;
  22126. };
  22127. /**
  22128. * get a material using its name
  22129. * @param {string} the material's name
  22130. * @return {BABYLON.Material|null} the material or null if none found.
  22131. */
  22132. Scene.prototype.getMaterialByName = function (name) {
  22133. for (var index = 0; index < this.materials.length; index++) {
  22134. if (this.materials[index].name === name) {
  22135. return this.materials[index];
  22136. }
  22137. }
  22138. return null;
  22139. };
  22140. Scene.prototype.getLensFlareSystemByName = function (name) {
  22141. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22142. if (this.lensFlareSystems[index].name === name) {
  22143. return this.lensFlareSystems[index];
  22144. }
  22145. }
  22146. return null;
  22147. };
  22148. Scene.prototype.getLensFlareSystemByID = function (id) {
  22149. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22150. if (this.lensFlareSystems[index].id === id) {
  22151. return this.lensFlareSystems[index];
  22152. }
  22153. }
  22154. return null;
  22155. };
  22156. Scene.prototype.getCameraByID = function (id) {
  22157. for (var index = 0; index < this.cameras.length; index++) {
  22158. if (this.cameras[index].id === id) {
  22159. return this.cameras[index];
  22160. }
  22161. }
  22162. return null;
  22163. };
  22164. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22165. for (var index = 0; index < this.cameras.length; index++) {
  22166. if (this.cameras[index].uniqueId === uniqueId) {
  22167. return this.cameras[index];
  22168. }
  22169. }
  22170. return null;
  22171. };
  22172. /**
  22173. * get a camera using its name
  22174. * @param {string} the camera's name
  22175. * @return {BABYLON.Camera|null} the camera or null if none found.
  22176. */
  22177. Scene.prototype.getCameraByName = function (name) {
  22178. for (var index = 0; index < this.cameras.length; index++) {
  22179. if (this.cameras[index].name === name) {
  22180. return this.cameras[index];
  22181. }
  22182. }
  22183. return null;
  22184. };
  22185. /**
  22186. * get a bone using its id
  22187. * @param {string} the bone's id
  22188. * @return {BABYLON.Bone|null} the bone or null if not found
  22189. */
  22190. Scene.prototype.getBoneByID = function (id) {
  22191. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22192. var skeleton = this.skeletons[skeletonIndex];
  22193. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22194. if (skeleton.bones[boneIndex].id === id) {
  22195. return skeleton.bones[boneIndex];
  22196. }
  22197. }
  22198. }
  22199. return null;
  22200. };
  22201. /**
  22202. * get a bone using its id
  22203. * @param {string} the bone's name
  22204. * @return {BABYLON.Bone|null} the bone or null if not found
  22205. */
  22206. Scene.prototype.getBoneByName = function (name) {
  22207. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22208. var skeleton = this.skeletons[skeletonIndex];
  22209. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22210. if (skeleton.bones[boneIndex].name === name) {
  22211. return skeleton.bones[boneIndex];
  22212. }
  22213. }
  22214. }
  22215. return null;
  22216. };
  22217. /**
  22218. * get a light node using its name
  22219. * @param {string} the light's name
  22220. * @return {BABYLON.Light|null} the light or null if none found.
  22221. */
  22222. Scene.prototype.getLightByName = function (name) {
  22223. for (var index = 0; index < this.lights.length; index++) {
  22224. if (this.lights[index].name === name) {
  22225. return this.lights[index];
  22226. }
  22227. }
  22228. return null;
  22229. };
  22230. /**
  22231. * get a light node using its ID
  22232. * @param {string} the light's id
  22233. * @return {BABYLON.Light|null} the light or null if none found.
  22234. */
  22235. Scene.prototype.getLightByID = function (id) {
  22236. for (var index = 0; index < this.lights.length; index++) {
  22237. if (this.lights[index].id === id) {
  22238. return this.lights[index];
  22239. }
  22240. }
  22241. return null;
  22242. };
  22243. /**
  22244. * get a light node using its scene-generated unique ID
  22245. * @param {number} the light's unique id
  22246. * @return {BABYLON.Light|null} the light or null if none found.
  22247. */
  22248. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22249. for (var index = 0; index < this.lights.length; index++) {
  22250. if (this.lights[index].uniqueId === uniqueId) {
  22251. return this.lights[index];
  22252. }
  22253. }
  22254. return null;
  22255. };
  22256. /**
  22257. * get a particle system by id
  22258. * @param id {number} the particle system id
  22259. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22260. */
  22261. Scene.prototype.getParticleSystemByID = function (id) {
  22262. for (var index = 0; index < this.particleSystems.length; index++) {
  22263. if (this.particleSystems[index].id === id) {
  22264. return this.particleSystems[index];
  22265. }
  22266. }
  22267. return null;
  22268. };
  22269. /**
  22270. * get a geometry using its ID
  22271. * @param {string} the geometry's id
  22272. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22273. */
  22274. Scene.prototype.getGeometryByID = function (id) {
  22275. for (var index = 0; index < this._geometries.length; index++) {
  22276. if (this._geometries[index].id === id) {
  22277. return this._geometries[index];
  22278. }
  22279. }
  22280. return null;
  22281. };
  22282. /**
  22283. * add a new geometry to this scene.
  22284. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22285. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22286. * @return {boolean} was the geometry added or not
  22287. */
  22288. Scene.prototype.pushGeometry = function (geometry, force) {
  22289. if (!force && this.getGeometryByID(geometry.id)) {
  22290. return false;
  22291. }
  22292. this._geometries.push(geometry);
  22293. //notify the collision coordinator
  22294. if (this.collisionCoordinator) {
  22295. this.collisionCoordinator.onGeometryAdded(geometry);
  22296. }
  22297. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22298. return true;
  22299. };
  22300. /**
  22301. * Removes an existing geometry
  22302. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22303. * @return {boolean} was the geometry removed or not
  22304. */
  22305. Scene.prototype.removeGeometry = function (geometry) {
  22306. var index = this._geometries.indexOf(geometry);
  22307. if (index > -1) {
  22308. this._geometries.splice(index, 1);
  22309. //notify the collision coordinator
  22310. if (this.collisionCoordinator) {
  22311. this.collisionCoordinator.onGeometryDeleted(geometry);
  22312. }
  22313. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22314. return true;
  22315. }
  22316. return false;
  22317. };
  22318. Scene.prototype.getGeometries = function () {
  22319. return this._geometries;
  22320. };
  22321. /**
  22322. * Get the first added mesh found of a given ID
  22323. * @param {string} id - the id to search for
  22324. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22325. */
  22326. Scene.prototype.getMeshByID = function (id) {
  22327. for (var index = 0; index < this.meshes.length; index++) {
  22328. if (this.meshes[index].id === id) {
  22329. return this.meshes[index];
  22330. }
  22331. }
  22332. return null;
  22333. };
  22334. Scene.prototype.getMeshesByID = function (id) {
  22335. return this.meshes.filter(function (m) {
  22336. return m.id === id;
  22337. });
  22338. };
  22339. /**
  22340. * Get the first added transform node found of a given ID
  22341. * @param {string} id - the id to search for
  22342. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22343. */
  22344. Scene.prototype.getTransformNodeByID = function (id) {
  22345. for (var index = 0; index < this.transformNodes.length; index++) {
  22346. if (this.transformNodes[index].id === id) {
  22347. return this.transformNodes[index];
  22348. }
  22349. }
  22350. return null;
  22351. };
  22352. Scene.prototype.getTransformNodesByID = function (id) {
  22353. return this.transformNodes.filter(function (m) {
  22354. return m.id === id;
  22355. });
  22356. };
  22357. /**
  22358. * Get a mesh with its auto-generated unique id
  22359. * @param {number} uniqueId - the unique id to search for
  22360. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22361. */
  22362. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22363. for (var index = 0; index < this.meshes.length; index++) {
  22364. if (this.meshes[index].uniqueId === uniqueId) {
  22365. return this.meshes[index];
  22366. }
  22367. }
  22368. return null;
  22369. };
  22370. /**
  22371. * Get a the last added mesh found of a given ID
  22372. * @param {string} id - the id to search for
  22373. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22374. */
  22375. Scene.prototype.getLastMeshByID = function (id) {
  22376. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22377. if (this.meshes[index].id === id) {
  22378. return this.meshes[index];
  22379. }
  22380. }
  22381. return null;
  22382. };
  22383. /**
  22384. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22385. * @param {string} id - the id to search for
  22386. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22387. */
  22388. Scene.prototype.getLastEntryByID = function (id) {
  22389. var index;
  22390. for (index = this.meshes.length - 1; index >= 0; index--) {
  22391. if (this.meshes[index].id === id) {
  22392. return this.meshes[index];
  22393. }
  22394. }
  22395. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22396. if (this.transformNodes[index].id === id) {
  22397. return this.transformNodes[index];
  22398. }
  22399. }
  22400. for (index = this.cameras.length - 1; index >= 0; index--) {
  22401. if (this.cameras[index].id === id) {
  22402. return this.cameras[index];
  22403. }
  22404. }
  22405. for (index = this.lights.length - 1; index >= 0; index--) {
  22406. if (this.lights[index].id === id) {
  22407. return this.lights[index];
  22408. }
  22409. }
  22410. return null;
  22411. };
  22412. Scene.prototype.getNodeByID = function (id) {
  22413. var mesh = this.getMeshByID(id);
  22414. if (mesh) {
  22415. return mesh;
  22416. }
  22417. var light = this.getLightByID(id);
  22418. if (light) {
  22419. return light;
  22420. }
  22421. var camera = this.getCameraByID(id);
  22422. if (camera) {
  22423. return camera;
  22424. }
  22425. var bone = this.getBoneByID(id);
  22426. return bone;
  22427. };
  22428. Scene.prototype.getNodeByName = function (name) {
  22429. var mesh = this.getMeshByName(name);
  22430. if (mesh) {
  22431. return mesh;
  22432. }
  22433. var light = this.getLightByName(name);
  22434. if (light) {
  22435. return light;
  22436. }
  22437. var camera = this.getCameraByName(name);
  22438. if (camera) {
  22439. return camera;
  22440. }
  22441. var bone = this.getBoneByName(name);
  22442. return bone;
  22443. };
  22444. Scene.prototype.getMeshByName = function (name) {
  22445. for (var index = 0; index < this.meshes.length; index++) {
  22446. if (this.meshes[index].name === name) {
  22447. return this.meshes[index];
  22448. }
  22449. }
  22450. return null;
  22451. };
  22452. Scene.prototype.getTransformNodeByName = function (name) {
  22453. for (var index = 0; index < this.transformNodes.length; index++) {
  22454. if (this.transformNodes[index].name === name) {
  22455. return this.transformNodes[index];
  22456. }
  22457. }
  22458. return null;
  22459. };
  22460. Scene.prototype.getSoundByName = function (name) {
  22461. var index;
  22462. if (BABYLON.AudioEngine) {
  22463. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22464. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22465. return this.mainSoundTrack.soundCollection[index];
  22466. }
  22467. }
  22468. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22469. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22470. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22471. return this.soundTracks[sdIndex].soundCollection[index];
  22472. }
  22473. }
  22474. }
  22475. }
  22476. return null;
  22477. };
  22478. Scene.prototype.getLastSkeletonByID = function (id) {
  22479. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22480. if (this.skeletons[index].id === id) {
  22481. return this.skeletons[index];
  22482. }
  22483. }
  22484. return null;
  22485. };
  22486. Scene.prototype.getSkeletonById = function (id) {
  22487. for (var index = 0; index < this.skeletons.length; index++) {
  22488. if (this.skeletons[index].id === id) {
  22489. return this.skeletons[index];
  22490. }
  22491. }
  22492. return null;
  22493. };
  22494. Scene.prototype.getSkeletonByName = function (name) {
  22495. for (var index = 0; index < this.skeletons.length; index++) {
  22496. if (this.skeletons[index].name === name) {
  22497. return this.skeletons[index];
  22498. }
  22499. }
  22500. return null;
  22501. };
  22502. Scene.prototype.getMorphTargetManagerById = function (id) {
  22503. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22504. if (this.morphTargetManagers[index].uniqueId === id) {
  22505. return this.morphTargetManagers[index];
  22506. }
  22507. }
  22508. return null;
  22509. };
  22510. Scene.prototype.isActiveMesh = function (mesh) {
  22511. return (this._activeMeshes.indexOf(mesh) !== -1);
  22512. };
  22513. /**
  22514. * Return a the first highlight layer of the scene with a given name.
  22515. * @param name The name of the highlight layer to look for.
  22516. * @return The highlight layer if found otherwise null.
  22517. */
  22518. Scene.prototype.getHighlightLayerByName = function (name) {
  22519. for (var index = 0; index < this.highlightLayers.length; index++) {
  22520. if (this.highlightLayers[index].name === name) {
  22521. return this.highlightLayers[index];
  22522. }
  22523. }
  22524. return null;
  22525. };
  22526. Object.defineProperty(Scene.prototype, "uid", {
  22527. /**
  22528. * Return a unique id as a string which can serve as an identifier for the scene
  22529. */
  22530. get: function () {
  22531. if (!this._uid) {
  22532. this._uid = BABYLON.Tools.RandomId();
  22533. }
  22534. return this._uid;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. /**
  22540. * Add an externaly attached data from its key.
  22541. * This method call will fail and return false, if such key already exists.
  22542. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22543. * @param key the unique key that identifies the data
  22544. * @param data the data object to associate to the key for this Engine instance
  22545. * @return true if no such key were already present and the data was added successfully, false otherwise
  22546. */
  22547. Scene.prototype.addExternalData = function (key, data) {
  22548. if (!this._externalData) {
  22549. this._externalData = new BABYLON.StringDictionary();
  22550. }
  22551. return this._externalData.add(key, data);
  22552. };
  22553. /**
  22554. * Get an externaly attached data from its key
  22555. * @param key the unique key that identifies the data
  22556. * @return the associated data, if present (can be null), or undefined if not present
  22557. */
  22558. Scene.prototype.getExternalData = function (key) {
  22559. if (!this._externalData) {
  22560. return null;
  22561. }
  22562. return this._externalData.get(key);
  22563. };
  22564. /**
  22565. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22566. * @param key the unique key that identifies the data
  22567. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22568. * @return the associated data, can be null if the factory returned null.
  22569. */
  22570. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22571. if (!this._externalData) {
  22572. this._externalData = new BABYLON.StringDictionary();
  22573. }
  22574. return this._externalData.getOrAddWithFactory(key, factory);
  22575. };
  22576. /**
  22577. * Remove an externaly attached data from the Engine instance
  22578. * @param key the unique key that identifies the data
  22579. * @return true if the data was successfully removed, false if it doesn't exist
  22580. */
  22581. Scene.prototype.removeExternalData = function (key) {
  22582. return this._externalData.remove(key);
  22583. };
  22584. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22585. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22586. if (mesh.showSubMeshesBoundingBox) {
  22587. var boundingInfo = subMesh.getBoundingInfo();
  22588. if (boundingInfo !== null && boundingInfo !== undefined) {
  22589. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22590. }
  22591. }
  22592. var material = subMesh.getMaterial();
  22593. if (material !== null && material !== undefined) {
  22594. // Render targets
  22595. if (material.getRenderTargetTextures !== undefined) {
  22596. if (this._processedMaterials.indexOf(material) === -1) {
  22597. this._processedMaterials.push(material);
  22598. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22599. }
  22600. }
  22601. // Dispatch
  22602. this._activeIndices.addCount(subMesh.indexCount, false);
  22603. this._renderingManager.dispatch(subMesh, mesh, material);
  22604. }
  22605. }
  22606. };
  22607. Scene.prototype._isInIntermediateRendering = function () {
  22608. return this._intermediateRendering;
  22609. };
  22610. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22611. this._activeMeshCandidateProvider = provider;
  22612. };
  22613. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22614. return this._activeMeshCandidateProvider;
  22615. };
  22616. /**
  22617. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22618. */
  22619. Scene.prototype.freezeActiveMeshes = function () {
  22620. this._evaluateActiveMeshes();
  22621. this._activeMeshesFrozen = true;
  22622. return this;
  22623. };
  22624. /**
  22625. * Use this function to restart evaluating active meshes on every frame
  22626. */
  22627. Scene.prototype.unfreezeActiveMeshes = function () {
  22628. this._activeMeshesFrozen = false;
  22629. return this;
  22630. };
  22631. Scene.prototype._evaluateActiveMeshes = function () {
  22632. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22633. return;
  22634. }
  22635. if (!this.activeCamera) {
  22636. return;
  22637. }
  22638. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22639. this.activeCamera._activeMeshes.reset();
  22640. this._activeMeshes.reset();
  22641. this._renderingManager.reset();
  22642. this._processedMaterials.reset();
  22643. this._activeParticleSystems.reset();
  22644. this._activeSkeletons.reset();
  22645. this._softwareSkinnedMeshes.reset();
  22646. if (this._boundingBoxRenderer) {
  22647. this._boundingBoxRenderer.reset();
  22648. }
  22649. // Meshes
  22650. var meshes;
  22651. var len;
  22652. var checkIsEnabled = true;
  22653. // Determine mesh candidates
  22654. if (this._activeMeshCandidateProvider !== undefined) {
  22655. // Use _activeMeshCandidateProvider
  22656. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22657. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22658. if (meshes !== undefined) {
  22659. len = meshes.length;
  22660. }
  22661. else {
  22662. len = 0;
  22663. }
  22664. }
  22665. else if (this._selectionOctree !== undefined) {
  22666. // Octree
  22667. var selection = this._selectionOctree.select(this._frustumPlanes);
  22668. meshes = selection.data;
  22669. len = selection.length;
  22670. }
  22671. else {
  22672. // Full scene traversal
  22673. len = this.meshes.length;
  22674. meshes = this.meshes;
  22675. }
  22676. // Check each mesh
  22677. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22678. mesh = meshes[meshIndex];
  22679. if (mesh.isBlocked) {
  22680. continue;
  22681. }
  22682. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22683. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22684. continue;
  22685. }
  22686. mesh.computeWorldMatrix();
  22687. // Intersections
  22688. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22689. this._meshesForIntersections.pushNoDuplicate(mesh);
  22690. }
  22691. // Switch to current LOD
  22692. meshLOD = mesh.getLOD(this.activeCamera);
  22693. if (meshLOD === undefined || meshLOD === null) {
  22694. continue;
  22695. }
  22696. mesh._preActivate();
  22697. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22698. this._activeMeshes.push(mesh);
  22699. this.activeCamera._activeMeshes.push(mesh);
  22700. mesh._activate(this._renderId);
  22701. if (meshLOD !== mesh) {
  22702. meshLOD._activate(this._renderId);
  22703. }
  22704. this._activeMesh(mesh, meshLOD);
  22705. }
  22706. }
  22707. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22708. // Particle systems
  22709. if (this.particlesEnabled) {
  22710. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22711. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22712. var particleSystem = this.particleSystems[particleIndex];
  22713. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22714. continue;
  22715. }
  22716. var emitter = particleSystem.emitter;
  22717. if (!emitter.position || emitter.isEnabled()) {
  22718. this._activeParticleSystems.push(particleSystem);
  22719. particleSystem.animate();
  22720. this._renderingManager.dispatchParticles(particleSystem);
  22721. }
  22722. }
  22723. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22724. }
  22725. };
  22726. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22727. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22728. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22729. mesh.skeleton.prepare();
  22730. }
  22731. if (!mesh.computeBonesUsingShaders) {
  22732. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22733. }
  22734. }
  22735. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22736. var boundingInfo = sourceMesh.getBoundingInfo();
  22737. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22738. }
  22739. if (mesh !== undefined && mesh !== null
  22740. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22741. // Submeshes Octrees
  22742. var len;
  22743. var subMeshes;
  22744. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22745. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22746. len = intersections.length;
  22747. subMeshes = intersections.data;
  22748. }
  22749. else {
  22750. subMeshes = mesh.subMeshes;
  22751. len = subMeshes.length;
  22752. }
  22753. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22754. subMesh = subMeshes[subIndex];
  22755. this._evaluateSubMesh(subMesh, mesh);
  22756. }
  22757. }
  22758. };
  22759. Scene.prototype.updateTransformMatrix = function (force) {
  22760. if (!this.activeCamera) {
  22761. return;
  22762. }
  22763. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22764. };
  22765. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22766. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22767. };
  22768. Scene.prototype._renderForCamera = function (camera) {
  22769. if (camera && camera._skipRendering) {
  22770. return;
  22771. }
  22772. var engine = this._engine;
  22773. this.activeCamera = camera;
  22774. if (!this.activeCamera)
  22775. throw new Error("Active camera not set");
  22776. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22777. // Viewport
  22778. engine.setViewport(this.activeCamera.viewport);
  22779. // Camera
  22780. this.resetCachedMaterial();
  22781. this._renderId++;
  22782. this.activeCamera.update();
  22783. this.updateTransformMatrix();
  22784. if (camera._alternateCamera) {
  22785. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22786. this._alternateRendering = true;
  22787. }
  22788. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22789. // Meshes
  22790. this._evaluateActiveMeshes();
  22791. // Software skinning
  22792. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22793. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22794. mesh.applySkeleton(mesh.skeleton);
  22795. }
  22796. // Render targets
  22797. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22798. var needsRestoreFrameBuffer = false;
  22799. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22800. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22801. }
  22802. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22803. this._intermediateRendering = true;
  22804. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22805. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22806. var renderTarget = this._renderTargets.data[renderIndex];
  22807. if (renderTarget._shouldRender()) {
  22808. this._renderId++;
  22809. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22810. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22811. }
  22812. }
  22813. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22814. this._intermediateRendering = false;
  22815. this._renderId++;
  22816. needsRestoreFrameBuffer = true; // Restore back buffer
  22817. }
  22818. // Render HighlightLayer Texture
  22819. var stencilState = this._engine.getStencilBuffer();
  22820. var renderhighlights = false;
  22821. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22822. this._intermediateRendering = true;
  22823. for (var i = 0; i < this.highlightLayers.length; i++) {
  22824. var highlightLayer = this.highlightLayers[i];
  22825. if (highlightLayer.shouldRender() &&
  22826. (!highlightLayer.camera ||
  22827. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22828. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22829. renderhighlights = true;
  22830. var renderTarget = highlightLayer._mainTexture;
  22831. if (renderTarget._shouldRender()) {
  22832. this._renderId++;
  22833. renderTarget.render(false, false);
  22834. needsRestoreFrameBuffer = true;
  22835. }
  22836. }
  22837. }
  22838. this._intermediateRendering = false;
  22839. this._renderId++;
  22840. }
  22841. if (needsRestoreFrameBuffer) {
  22842. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22843. }
  22844. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22845. // Prepare Frame
  22846. this.postProcessManager._prepareFrame();
  22847. // Backgrounds
  22848. var layerIndex;
  22849. var layer;
  22850. if (this.layers.length) {
  22851. engine.setDepthBuffer(false);
  22852. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22853. layer = this.layers[layerIndex];
  22854. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22855. layer.render();
  22856. }
  22857. }
  22858. engine.setDepthBuffer(true);
  22859. }
  22860. // Activate HighlightLayer stencil
  22861. if (renderhighlights) {
  22862. this._engine.setStencilBuffer(true);
  22863. }
  22864. // Render
  22865. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22866. this._renderingManager.render(null, null, true, true);
  22867. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22868. // Restore HighlightLayer stencil
  22869. if (renderhighlights) {
  22870. this._engine.setStencilBuffer(stencilState);
  22871. }
  22872. // Bounding boxes
  22873. if (this._boundingBoxRenderer) {
  22874. this._boundingBoxRenderer.render();
  22875. }
  22876. // Lens flares
  22877. if (this.lensFlaresEnabled) {
  22878. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22879. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22880. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22881. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22882. lensFlareSystem.render();
  22883. }
  22884. }
  22885. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22886. }
  22887. // Foregrounds
  22888. if (this.layers.length) {
  22889. engine.setDepthBuffer(false);
  22890. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22891. layer = this.layers[layerIndex];
  22892. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22893. layer.render();
  22894. }
  22895. }
  22896. engine.setDepthBuffer(true);
  22897. }
  22898. // Highlight Layer
  22899. if (renderhighlights) {
  22900. engine.setDepthBuffer(false);
  22901. for (var i = 0; i < this.highlightLayers.length; i++) {
  22902. if (this.highlightLayers[i].shouldRender()) {
  22903. this.highlightLayers[i].render();
  22904. }
  22905. }
  22906. engine.setDepthBuffer(true);
  22907. }
  22908. // Finalize frame
  22909. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22910. // Reset some special arrays
  22911. this._renderTargets.reset();
  22912. this._alternateRendering = false;
  22913. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22914. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22915. };
  22916. Scene.prototype._processSubCameras = function (camera) {
  22917. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22918. this._renderForCamera(camera);
  22919. return;
  22920. }
  22921. // Update camera
  22922. if (this.activeCamera) {
  22923. this.activeCamera.update();
  22924. }
  22925. // rig cameras
  22926. for (var index = 0; index < camera._rigCameras.length; index++) {
  22927. this._renderForCamera(camera._rigCameras[index]);
  22928. }
  22929. this.activeCamera = camera;
  22930. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22931. };
  22932. Scene.prototype._checkIntersections = function () {
  22933. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22934. var sourceMesh = this._meshesForIntersections.data[index];
  22935. if (!sourceMesh.actionManager) {
  22936. continue;
  22937. }
  22938. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22939. var action = sourceMesh.actionManager.actions[actionIndex];
  22940. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22941. var parameters = action.getTriggerParameter();
  22942. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22943. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22944. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22945. if (areIntersecting && currentIntersectionInProgress === -1) {
  22946. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22947. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22948. sourceMesh._intersectionsInProgress.push(otherMesh);
  22949. }
  22950. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22951. sourceMesh._intersectionsInProgress.push(otherMesh);
  22952. }
  22953. }
  22954. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22955. //They intersected, and now they don't.
  22956. //is this trigger an exit trigger? execute an event.
  22957. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22958. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22959. }
  22960. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22961. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22962. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22963. }
  22964. }
  22965. }
  22966. }
  22967. }
  22968. };
  22969. Scene.prototype.render = function () {
  22970. if (this.isDisposed) {
  22971. return;
  22972. }
  22973. this._activeParticles.fetchNewFrame();
  22974. this._totalVertices.fetchNewFrame();
  22975. this._activeIndices.fetchNewFrame();
  22976. this._activeBones.fetchNewFrame();
  22977. this._meshesForIntersections.reset();
  22978. this.resetCachedMaterial();
  22979. this.onBeforeAnimationsObservable.notifyObservers(this);
  22980. // Actions
  22981. if (this.actionManager) {
  22982. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22983. }
  22984. //Simplification Queue
  22985. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22986. this.simplificationQueue.executeNext();
  22987. }
  22988. if (this._engine.isDeterministicLockStep()) {
  22989. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22990. var defaultFPS = (60.0 / 1000.0);
  22991. var defaultFrameTime = 1000 / 60; // frame time in MS
  22992. if (this._physicsEngine) {
  22993. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22994. }
  22995. var stepsTaken = 0;
  22996. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22997. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22998. internalSteps = Math.min(internalSteps, maxSubSteps);
  22999. do {
  23000. this.onBeforeStepObservable.notifyObservers(this);
  23001. // Animations
  23002. this._animationRatio = defaultFrameTime * defaultFPS;
  23003. this._animate();
  23004. this.onAfterAnimationsObservable.notifyObservers(this);
  23005. // Physics
  23006. if (this._physicsEngine) {
  23007. this.onBeforePhysicsObservable.notifyObservers(this);
  23008. this._physicsEngine._step(defaultFrameTime / 1000);
  23009. this.onAfterPhysicsObservable.notifyObservers(this);
  23010. }
  23011. this.onAfterStepObservable.notifyObservers(this);
  23012. this._currentStepId++;
  23013. stepsTaken++;
  23014. deltaTime -= defaultFrameTime;
  23015. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23016. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23017. }
  23018. else {
  23019. // Animations
  23020. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23021. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23022. this._animate();
  23023. this.onAfterAnimationsObservable.notifyObservers(this);
  23024. // Physics
  23025. if (this._physicsEngine) {
  23026. this.onBeforePhysicsObservable.notifyObservers(this);
  23027. this._physicsEngine._step(deltaTime / 1000.0);
  23028. this.onAfterPhysicsObservable.notifyObservers(this);
  23029. }
  23030. }
  23031. // update gamepad manager
  23032. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23033. this._gamepadManager._checkGamepadsStatus();
  23034. }
  23035. // Before render
  23036. this.onBeforeRenderObservable.notifyObservers(this);
  23037. // Customs render targets
  23038. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23039. var engine = this.getEngine();
  23040. var currentActiveCamera = this.activeCamera;
  23041. if (this.renderTargetsEnabled) {
  23042. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23043. this._intermediateRendering = true;
  23044. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23045. var renderTarget = this.customRenderTargets[customIndex];
  23046. if (renderTarget._shouldRender()) {
  23047. this._renderId++;
  23048. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23049. if (!this.activeCamera)
  23050. throw new Error("Active camera not set");
  23051. // Viewport
  23052. engine.setViewport(this.activeCamera.viewport);
  23053. // Camera
  23054. this.updateTransformMatrix();
  23055. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23056. }
  23057. }
  23058. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23059. this._intermediateRendering = false;
  23060. this._renderId++;
  23061. }
  23062. // Restore back buffer
  23063. if (this.customRenderTargets.length > 0) {
  23064. engine.restoreDefaultFramebuffer();
  23065. }
  23066. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23067. this.activeCamera = currentActiveCamera;
  23068. // Procedural textures
  23069. if (this.proceduralTexturesEnabled) {
  23070. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23071. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23072. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23073. if (proceduralTexture._shouldRender()) {
  23074. proceduralTexture.render();
  23075. }
  23076. }
  23077. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23078. }
  23079. // Clear
  23080. if (this.autoClearDepthAndStencil || this.autoClear) {
  23081. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23082. }
  23083. // Shadows
  23084. if (this.shadowsEnabled) {
  23085. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23086. var light = this.lights[lightIndex];
  23087. var shadowGenerator = light.getShadowGenerator();
  23088. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23089. var shadowMap = (shadowGenerator.getShadowMap());
  23090. if (this.textures.indexOf(shadowMap) !== -1) {
  23091. this._renderTargets.push(shadowMap);
  23092. }
  23093. }
  23094. }
  23095. }
  23096. // Depth renderer
  23097. if (this._depthRenderer) {
  23098. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23099. }
  23100. // Geometry renderer
  23101. if (this._geometryBufferRenderer) {
  23102. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23103. }
  23104. // RenderPipeline
  23105. if (this._postProcessRenderPipelineManager) {
  23106. this._postProcessRenderPipelineManager.update();
  23107. }
  23108. // Multi-cameras?
  23109. if (this.activeCameras.length > 0) {
  23110. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23111. if (cameraIndex > 0) {
  23112. this._engine.clear(null, false, true, true);
  23113. }
  23114. this._processSubCameras(this.activeCameras[cameraIndex]);
  23115. }
  23116. }
  23117. else {
  23118. if (!this.activeCamera) {
  23119. throw new Error("No camera defined");
  23120. }
  23121. this._processSubCameras(this.activeCamera);
  23122. }
  23123. // Intersection checks
  23124. this._checkIntersections();
  23125. // Update the audio listener attached to the camera
  23126. if (BABYLON.AudioEngine) {
  23127. this._updateAudioParameters();
  23128. }
  23129. // After render
  23130. if (this.afterRender) {
  23131. this.afterRender();
  23132. }
  23133. this.onAfterRenderObservable.notifyObservers(this);
  23134. // Cleaning
  23135. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23136. var data = this._toBeDisposed.data[index];
  23137. if (data) {
  23138. data.dispose();
  23139. }
  23140. this._toBeDisposed[index] = null;
  23141. }
  23142. this._toBeDisposed.reset();
  23143. if (this.dumpNextRenderTargets) {
  23144. this.dumpNextRenderTargets = false;
  23145. }
  23146. this._activeBones.addCount(0, true);
  23147. this._activeIndices.addCount(0, true);
  23148. this._activeParticles.addCount(0, true);
  23149. };
  23150. Scene.prototype._updateAudioParameters = function () {
  23151. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23152. return;
  23153. }
  23154. var listeningCamera;
  23155. var audioEngine = BABYLON.Engine.audioEngine;
  23156. if (this.activeCameras.length > 0) {
  23157. listeningCamera = this.activeCameras[0];
  23158. }
  23159. else {
  23160. listeningCamera = this.activeCamera;
  23161. }
  23162. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23163. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23164. // for VR cameras
  23165. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23166. listeningCamera = listeningCamera.rigCameras[0];
  23167. }
  23168. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23169. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23170. cameraDirection.normalize();
  23171. // To avoid some errors on GearVR
  23172. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23173. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23174. }
  23175. var i;
  23176. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23177. var sound = this.mainSoundTrack.soundCollection[i];
  23178. if (sound.useCustomAttenuation) {
  23179. sound.updateDistanceFromListener();
  23180. }
  23181. }
  23182. for (i = 0; i < this.soundTracks.length; i++) {
  23183. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23184. sound = this.soundTracks[i].soundCollection[j];
  23185. if (sound.useCustomAttenuation) {
  23186. sound.updateDistanceFromListener();
  23187. }
  23188. }
  23189. }
  23190. }
  23191. };
  23192. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23193. // Audio
  23194. get: function () {
  23195. return this._audioEnabled;
  23196. },
  23197. set: function (value) {
  23198. this._audioEnabled = value;
  23199. if (BABYLON.AudioEngine) {
  23200. if (this._audioEnabled) {
  23201. this._enableAudio();
  23202. }
  23203. else {
  23204. this._disableAudio();
  23205. }
  23206. }
  23207. },
  23208. enumerable: true,
  23209. configurable: true
  23210. });
  23211. Scene.prototype._disableAudio = function () {
  23212. var i;
  23213. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23214. this.mainSoundTrack.soundCollection[i].pause();
  23215. }
  23216. for (i = 0; i < this.soundTracks.length; i++) {
  23217. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23218. this.soundTracks[i].soundCollection[j].pause();
  23219. }
  23220. }
  23221. };
  23222. Scene.prototype._enableAudio = function () {
  23223. var i;
  23224. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23225. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23226. this.mainSoundTrack.soundCollection[i].play();
  23227. }
  23228. }
  23229. for (i = 0; i < this.soundTracks.length; i++) {
  23230. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23231. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23232. this.soundTracks[i].soundCollection[j].play();
  23233. }
  23234. }
  23235. }
  23236. };
  23237. Object.defineProperty(Scene.prototype, "headphone", {
  23238. get: function () {
  23239. return this._headphone;
  23240. },
  23241. set: function (value) {
  23242. this._headphone = value;
  23243. if (BABYLON.AudioEngine) {
  23244. if (this._headphone) {
  23245. this._switchAudioModeForHeadphones();
  23246. }
  23247. else {
  23248. this._switchAudioModeForNormalSpeakers();
  23249. }
  23250. }
  23251. },
  23252. enumerable: true,
  23253. configurable: true
  23254. });
  23255. Scene.prototype._switchAudioModeForHeadphones = function () {
  23256. this.mainSoundTrack.switchPanningModelToHRTF();
  23257. for (var i = 0; i < this.soundTracks.length; i++) {
  23258. this.soundTracks[i].switchPanningModelToHRTF();
  23259. }
  23260. };
  23261. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23262. this.mainSoundTrack.switchPanningModelToEqualPower();
  23263. for (var i = 0; i < this.soundTracks.length; i++) {
  23264. this.soundTracks[i].switchPanningModelToEqualPower();
  23265. }
  23266. };
  23267. Scene.prototype.enableDepthRenderer = function () {
  23268. if (this._depthRenderer) {
  23269. return this._depthRenderer;
  23270. }
  23271. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23272. return this._depthRenderer;
  23273. };
  23274. Scene.prototype.disableDepthRenderer = function () {
  23275. if (!this._depthRenderer) {
  23276. return;
  23277. }
  23278. this._depthRenderer.dispose();
  23279. this._depthRenderer = null;
  23280. };
  23281. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23282. if (ratio === void 0) { ratio = 1; }
  23283. if (this._geometryBufferRenderer) {
  23284. return this._geometryBufferRenderer;
  23285. }
  23286. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23287. if (!this._geometryBufferRenderer.isSupported) {
  23288. this._geometryBufferRenderer = null;
  23289. }
  23290. return this._geometryBufferRenderer;
  23291. };
  23292. Scene.prototype.disableGeometryBufferRenderer = function () {
  23293. if (!this._geometryBufferRenderer) {
  23294. return;
  23295. }
  23296. this._geometryBufferRenderer.dispose();
  23297. this._geometryBufferRenderer = null;
  23298. };
  23299. Scene.prototype.freezeMaterials = function () {
  23300. for (var i = 0; i < this.materials.length; i++) {
  23301. this.materials[i].freeze();
  23302. }
  23303. };
  23304. Scene.prototype.unfreezeMaterials = function () {
  23305. for (var i = 0; i < this.materials.length; i++) {
  23306. this.materials[i].unfreeze();
  23307. }
  23308. };
  23309. Scene.prototype.dispose = function () {
  23310. this.beforeRender = null;
  23311. this.afterRender = null;
  23312. this.skeletons = [];
  23313. this.morphTargetManagers = [];
  23314. this.importedMeshesFiles = new Array();
  23315. this.stopAllAnimations();
  23316. this.resetCachedMaterial();
  23317. if (this._depthRenderer) {
  23318. this._depthRenderer.dispose();
  23319. }
  23320. if (this._gamepadManager) {
  23321. this._gamepadManager.dispose();
  23322. this._gamepadManager = null;
  23323. }
  23324. // Smart arrays
  23325. if (this.activeCamera) {
  23326. this.activeCamera._activeMeshes.dispose();
  23327. this.activeCamera = null;
  23328. }
  23329. this._activeMeshes.dispose();
  23330. this._renderingManager.dispose();
  23331. this._processedMaterials.dispose();
  23332. this._activeParticleSystems.dispose();
  23333. this._activeSkeletons.dispose();
  23334. this._softwareSkinnedMeshes.dispose();
  23335. this._renderTargets.dispose();
  23336. if (this._boundingBoxRenderer) {
  23337. this._boundingBoxRenderer.dispose();
  23338. }
  23339. this._meshesForIntersections.dispose();
  23340. this._toBeDisposed.dispose();
  23341. // Abort active requests
  23342. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23343. var request = _a[_i];
  23344. request.abort();
  23345. }
  23346. // Debug layer
  23347. if (this._debugLayer) {
  23348. this._debugLayer.hide();
  23349. }
  23350. // Events
  23351. this.onDisposeObservable.notifyObservers(this);
  23352. this.onDisposeObservable.clear();
  23353. this.onBeforeRenderObservable.clear();
  23354. this.onAfterRenderObservable.clear();
  23355. this.OnBeforeRenderTargetsRenderObservable.clear();
  23356. this.OnAfterRenderTargetsRenderObservable.clear();
  23357. this.onAfterStepObservable.clear();
  23358. this.onBeforeStepObservable.clear();
  23359. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23360. this.onAfterActiveMeshesEvaluationObservable.clear();
  23361. this.onBeforeParticlesRenderingObservable.clear();
  23362. this.onAfterParticlesRenderingObservable.clear();
  23363. this.onBeforeSpritesRenderingObservable.clear();
  23364. this.onAfterSpritesRenderingObservable.clear();
  23365. this.onBeforeDrawPhaseObservable.clear();
  23366. this.onAfterDrawPhaseObservable.clear();
  23367. this.onBeforePhysicsObservable.clear();
  23368. this.onAfterPhysicsObservable.clear();
  23369. this.onBeforeAnimationsObservable.clear();
  23370. this.onAfterAnimationsObservable.clear();
  23371. this.onDataLoadedObservable.clear();
  23372. this.detachControl();
  23373. // Release sounds & sounds tracks
  23374. if (BABYLON.AudioEngine) {
  23375. this.disposeSounds();
  23376. }
  23377. // VR Helper
  23378. if (this.VRHelper) {
  23379. this.VRHelper.dispose();
  23380. }
  23381. // Detach cameras
  23382. var canvas = this._engine.getRenderingCanvas();
  23383. if (canvas) {
  23384. var index;
  23385. for (index = 0; index < this.cameras.length; index++) {
  23386. this.cameras[index].detachControl(canvas);
  23387. }
  23388. }
  23389. // Release animation groups
  23390. while (this.animationGroups.length) {
  23391. this.animationGroups[0].dispose();
  23392. }
  23393. // Release lights
  23394. while (this.lights.length) {
  23395. this.lights[0].dispose();
  23396. }
  23397. // Release meshes
  23398. while (this.meshes.length) {
  23399. this.meshes[0].dispose(true);
  23400. }
  23401. while (this.transformNodes.length) {
  23402. this.removeTransformNode(this.transformNodes[0]);
  23403. }
  23404. // Release cameras
  23405. while (this.cameras.length) {
  23406. this.cameras[0].dispose();
  23407. }
  23408. // Release materials
  23409. if (this.defaultMaterial) {
  23410. this.defaultMaterial.dispose();
  23411. }
  23412. while (this.multiMaterials.length) {
  23413. this.multiMaterials[0].dispose();
  23414. }
  23415. while (this.materials.length) {
  23416. this.materials[0].dispose();
  23417. }
  23418. // Release particles
  23419. while (this.particleSystems.length) {
  23420. this.particleSystems[0].dispose();
  23421. }
  23422. // Release sprites
  23423. while (this.spriteManagers.length) {
  23424. this.spriteManagers[0].dispose();
  23425. }
  23426. // Release postProcesses
  23427. while (this.postProcesses.length) {
  23428. this.postProcesses[0].dispose();
  23429. }
  23430. // Release layers
  23431. while (this.layers.length) {
  23432. this.layers[0].dispose();
  23433. }
  23434. while (this.highlightLayers.length) {
  23435. this.highlightLayers[0].dispose();
  23436. }
  23437. // Release textures
  23438. while (this.textures.length) {
  23439. this.textures[0].dispose();
  23440. }
  23441. // Release UBO
  23442. this._sceneUbo.dispose();
  23443. if (this._alternateSceneUbo) {
  23444. this._alternateSceneUbo.dispose();
  23445. }
  23446. // Post-processes
  23447. this.postProcessManager.dispose();
  23448. if (this._postProcessRenderPipelineManager) {
  23449. this._postProcessRenderPipelineManager.dispose();
  23450. }
  23451. // Physics
  23452. if (this._physicsEngine) {
  23453. this.disablePhysicsEngine();
  23454. }
  23455. // Remove from engine
  23456. index = this._engine.scenes.indexOf(this);
  23457. if (index > -1) {
  23458. this._engine.scenes.splice(index, 1);
  23459. }
  23460. this._engine.wipeCaches(true);
  23461. this._isDisposed = true;
  23462. };
  23463. Object.defineProperty(Scene.prototype, "isDisposed", {
  23464. get: function () {
  23465. return this._isDisposed;
  23466. },
  23467. enumerable: true,
  23468. configurable: true
  23469. });
  23470. // Release sounds & sounds tracks
  23471. Scene.prototype.disposeSounds = function () {
  23472. if (!this._mainSoundTrack) {
  23473. return;
  23474. }
  23475. this.mainSoundTrack.dispose();
  23476. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23477. this.soundTracks[scIndex].dispose();
  23478. }
  23479. };
  23480. // Octrees
  23481. Scene.prototype.getWorldExtends = function () {
  23482. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23483. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23484. for (var index = 0; index < this.meshes.length; index++) {
  23485. var mesh = this.meshes[index];
  23486. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23487. continue;
  23488. }
  23489. mesh.computeWorldMatrix(true);
  23490. var boundingInfo = mesh.getBoundingInfo();
  23491. var minBox = boundingInfo.boundingBox.minimumWorld;
  23492. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23493. BABYLON.Tools.CheckExtends(minBox, min, max);
  23494. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23495. }
  23496. return {
  23497. min: min,
  23498. max: max
  23499. };
  23500. };
  23501. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23502. if (maxCapacity === void 0) { maxCapacity = 64; }
  23503. if (maxDepth === void 0) { maxDepth = 2; }
  23504. if (!this._selectionOctree) {
  23505. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23506. }
  23507. var worldExtends = this.getWorldExtends();
  23508. // Update octree
  23509. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23510. return this._selectionOctree;
  23511. };
  23512. // Picking
  23513. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23514. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23515. var result = BABYLON.Ray.Zero();
  23516. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23517. return result;
  23518. };
  23519. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23520. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23521. var engine = this._engine;
  23522. if (!camera) {
  23523. if (!this.activeCamera)
  23524. throw new Error("Active camera not set");
  23525. camera = this.activeCamera;
  23526. }
  23527. var cameraViewport = camera.viewport;
  23528. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23529. // Moving coordinates to local viewport world
  23530. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23531. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23532. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23533. return this;
  23534. };
  23535. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23536. var result = BABYLON.Ray.Zero();
  23537. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23538. return result;
  23539. };
  23540. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23541. if (!BABYLON.PickingInfo) {
  23542. return this;
  23543. }
  23544. var engine = this._engine;
  23545. if (!camera) {
  23546. if (!this.activeCamera)
  23547. throw new Error("Active camera not set");
  23548. camera = this.activeCamera;
  23549. }
  23550. var cameraViewport = camera.viewport;
  23551. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23552. var identity = BABYLON.Matrix.Identity();
  23553. // Moving coordinates to local viewport world
  23554. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23555. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23556. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23557. return this;
  23558. };
  23559. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23560. if (!BABYLON.PickingInfo) {
  23561. return null;
  23562. }
  23563. var pickingInfo = null;
  23564. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23565. var mesh = this.meshes[meshIndex];
  23566. if (predicate) {
  23567. if (!predicate(mesh)) {
  23568. continue;
  23569. }
  23570. }
  23571. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23572. continue;
  23573. }
  23574. var world = mesh.getWorldMatrix();
  23575. var ray = rayFunction(world);
  23576. var result = mesh.intersects(ray, fastCheck);
  23577. if (!result || !result.hit)
  23578. continue;
  23579. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23580. continue;
  23581. pickingInfo = result;
  23582. if (fastCheck) {
  23583. break;
  23584. }
  23585. }
  23586. return pickingInfo || new BABYLON.PickingInfo();
  23587. };
  23588. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23589. if (!BABYLON.PickingInfo) {
  23590. return null;
  23591. }
  23592. var pickingInfos = new Array();
  23593. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23594. var mesh = this.meshes[meshIndex];
  23595. if (predicate) {
  23596. if (!predicate(mesh)) {
  23597. continue;
  23598. }
  23599. }
  23600. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23601. continue;
  23602. }
  23603. var world = mesh.getWorldMatrix();
  23604. var ray = rayFunction(world);
  23605. var result = mesh.intersects(ray, false);
  23606. if (!result || !result.hit)
  23607. continue;
  23608. pickingInfos.push(result);
  23609. }
  23610. return pickingInfos;
  23611. };
  23612. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23613. if (!BABYLON.PickingInfo) {
  23614. return null;
  23615. }
  23616. var pickingInfo = null;
  23617. if (!camera) {
  23618. if (!this.activeCamera) {
  23619. return null;
  23620. }
  23621. camera = this.activeCamera;
  23622. }
  23623. if (this.spriteManagers.length > 0) {
  23624. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23625. var spriteManager = this.spriteManagers[spriteIndex];
  23626. if (!spriteManager.isPickable) {
  23627. continue;
  23628. }
  23629. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23630. if (!result || !result.hit)
  23631. continue;
  23632. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23633. continue;
  23634. pickingInfo = result;
  23635. if (fastCheck) {
  23636. break;
  23637. }
  23638. }
  23639. }
  23640. return pickingInfo || new BABYLON.PickingInfo();
  23641. };
  23642. /** Launch a ray to try to pick a mesh in the scene
  23643. * @param x position on screen
  23644. * @param y position on screen
  23645. * @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
  23646. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23647. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23648. */
  23649. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23650. var _this = this;
  23651. if (!BABYLON.PickingInfo) {
  23652. return null;
  23653. }
  23654. return this._internalPick(function (world) {
  23655. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23656. return _this._tempPickingRay;
  23657. }, predicate, fastCheck);
  23658. };
  23659. /** Launch a ray to try to pick a sprite in the scene
  23660. * @param x position on screen
  23661. * @param y position on screen
  23662. * @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
  23663. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23664. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23665. */
  23666. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23667. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23668. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23669. };
  23670. /** Use the given ray to pick a mesh in the scene
  23671. * @param ray The ray to use to pick meshes
  23672. * @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
  23673. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23674. */
  23675. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23676. var _this = this;
  23677. return this._internalPick(function (world) {
  23678. if (!_this._pickWithRayInverseMatrix) {
  23679. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23680. }
  23681. world.invertToRef(_this._pickWithRayInverseMatrix);
  23682. if (!_this._cachedRayForTransform) {
  23683. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23684. }
  23685. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23686. return _this._cachedRayForTransform;
  23687. }, predicate, fastCheck);
  23688. };
  23689. /**
  23690. * Launch a ray to try to pick a mesh in the scene
  23691. * @param x X position on screen
  23692. * @param y Y position on screen
  23693. * @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
  23694. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23695. */
  23696. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23697. var _this = this;
  23698. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23699. };
  23700. /**
  23701. * Launch a ray to try to pick a mesh in the scene
  23702. * @param ray Ray to use
  23703. * @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
  23704. */
  23705. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23706. var _this = this;
  23707. return this._internalMultiPick(function (world) {
  23708. if (!_this._pickWithRayInverseMatrix) {
  23709. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23710. }
  23711. world.invertToRef(_this._pickWithRayInverseMatrix);
  23712. if (!_this._cachedRayForTransform) {
  23713. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23714. }
  23715. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23716. return _this._cachedRayForTransform;
  23717. }, predicate);
  23718. };
  23719. Scene.prototype.setPointerOverMesh = function (mesh) {
  23720. if (this._pointerOverMesh === mesh) {
  23721. return;
  23722. }
  23723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23725. }
  23726. this._pointerOverMesh = mesh;
  23727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23729. }
  23730. };
  23731. Scene.prototype.getPointerOverMesh = function () {
  23732. return this._pointerOverMesh;
  23733. };
  23734. Scene.prototype.setPointerOverSprite = function (sprite) {
  23735. if (this._pointerOverSprite === sprite) {
  23736. return;
  23737. }
  23738. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23739. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23740. }
  23741. this._pointerOverSprite = sprite;
  23742. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23743. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23744. }
  23745. };
  23746. Scene.prototype.getPointerOverSprite = function () {
  23747. return this._pointerOverSprite;
  23748. };
  23749. // Physics
  23750. Scene.prototype.getPhysicsEngine = function () {
  23751. return this._physicsEngine;
  23752. };
  23753. /**
  23754. * Enables physics to the current scene
  23755. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23756. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23757. * @return {boolean} was the physics engine initialized
  23758. */
  23759. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23760. if (gravity === void 0) { gravity = null; }
  23761. if (this._physicsEngine) {
  23762. return true;
  23763. }
  23764. try {
  23765. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23766. return true;
  23767. }
  23768. catch (e) {
  23769. BABYLON.Tools.Error(e.message);
  23770. return false;
  23771. }
  23772. };
  23773. Scene.prototype.disablePhysicsEngine = function () {
  23774. if (!this._physicsEngine) {
  23775. return;
  23776. }
  23777. this._physicsEngine.dispose();
  23778. this._physicsEngine = null;
  23779. };
  23780. Scene.prototype.isPhysicsEnabled = function () {
  23781. return this._physicsEngine !== undefined;
  23782. };
  23783. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23784. var mesh = compound.parts[0].mesh;
  23785. if (mesh.physicsImpostor) {
  23786. mesh.physicsImpostor.dispose();
  23787. mesh.physicsImpostor = null;
  23788. }
  23789. };
  23790. // Misc.
  23791. Scene.prototype._rebuildGeometries = function () {
  23792. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23793. var geometry = _a[_i];
  23794. geometry._rebuild();
  23795. }
  23796. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23797. var mesh = _c[_b];
  23798. mesh._rebuild();
  23799. }
  23800. if (this.postProcessManager) {
  23801. this.postProcessManager._rebuild();
  23802. }
  23803. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23804. var layer = _e[_d];
  23805. layer._rebuild();
  23806. }
  23807. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23808. var highlightLayer = _g[_f];
  23809. highlightLayer._rebuild();
  23810. }
  23811. if (this._boundingBoxRenderer) {
  23812. this._boundingBoxRenderer._rebuild();
  23813. }
  23814. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23815. var system = _j[_h];
  23816. system.rebuild();
  23817. }
  23818. if (this._postProcessRenderPipelineManager) {
  23819. this._postProcessRenderPipelineManager._rebuild();
  23820. }
  23821. };
  23822. Scene.prototype._rebuildTextures = function () {
  23823. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23824. var texture = _a[_i];
  23825. texture._rebuild();
  23826. }
  23827. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23828. };
  23829. /**
  23830. * Creates a default light for the scene.
  23831. * @param replace Whether to replace the existing lights in the scene.
  23832. */
  23833. Scene.prototype.createDefaultLight = function (replace) {
  23834. if (replace === void 0) { replace = false; }
  23835. // Dispose existing light in replace mode.
  23836. if (replace) {
  23837. if (this.lights) {
  23838. for (var i = 0; i < this.lights.length; i++) {
  23839. this.lights[i].dispose();
  23840. }
  23841. }
  23842. }
  23843. // Light
  23844. if (this.lights.length === 0) {
  23845. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23846. }
  23847. };
  23848. /**
  23849. * Creates a default camera for the scene.
  23850. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  23851. * @param replace Whether to replace the existing active camera in the scene.
  23852. * @param attachCameraControls Whether to attach camera controls to the canvas.
  23853. */
  23854. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  23855. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23856. if (replace === void 0) { replace = false; }
  23857. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23858. // Dispose existing camera in replace mode.
  23859. if (replace) {
  23860. if (this.activeCamera) {
  23861. this.activeCamera.dispose();
  23862. this.activeCamera = null;
  23863. }
  23864. }
  23865. // Camera
  23866. if (!this.activeCamera) {
  23867. var worldExtends = this.getWorldExtends();
  23868. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23869. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23870. var camera;
  23871. var radius = worldSize.length() * 1.5;
  23872. if (createArcRotateCamera) {
  23873. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23874. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23875. arcRotateCamera.wheelPrecision = 100 / radius;
  23876. camera = arcRotateCamera;
  23877. }
  23878. else {
  23879. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23880. freeCamera.setTarget(worldCenter);
  23881. camera = freeCamera;
  23882. }
  23883. camera.minZ = radius * 0.01;
  23884. camera.maxZ = radius * 1000;
  23885. camera.speed = radius * 0.2;
  23886. this.activeCamera = camera;
  23887. var canvas = this.getEngine().getRenderingCanvas();
  23888. if (attachCameraControls && canvas) {
  23889. camera.attachControl(canvas);
  23890. }
  23891. }
  23892. };
  23893. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23894. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23895. if (replace === void 0) { replace = false; }
  23896. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23897. this.createDefaultLight(replace);
  23898. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  23899. };
  23900. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23901. if (pbr === void 0) { pbr = false; }
  23902. if (scale === void 0) { scale = 1000; }
  23903. if (blur === void 0) { blur = 0; }
  23904. if (environmentTexture) {
  23905. this.environmentTexture = environmentTexture;
  23906. }
  23907. if (!this.environmentTexture) {
  23908. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23909. return null;
  23910. }
  23911. // Skybox
  23912. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23913. if (pbr) {
  23914. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23915. hdrSkyboxMaterial.backFaceCulling = false;
  23916. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23917. if (hdrSkyboxMaterial.reflectionTexture) {
  23918. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23919. }
  23920. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23921. hdrSkyboxMaterial.disableLighting = true;
  23922. hdrSkyboxMaterial.twoSidedLighting = true;
  23923. hdrSkybox.infiniteDistance = true;
  23924. hdrSkybox.material = hdrSkyboxMaterial;
  23925. }
  23926. else {
  23927. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23928. skyboxMaterial.backFaceCulling = false;
  23929. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23930. if (skyboxMaterial.reflectionTexture) {
  23931. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23932. }
  23933. skyboxMaterial.disableLighting = true;
  23934. hdrSkybox.infiniteDistance = true;
  23935. hdrSkybox.material = skyboxMaterial;
  23936. }
  23937. return hdrSkybox;
  23938. };
  23939. Scene.prototype.createDefaultEnvironment = function (options) {
  23940. if (BABYLON.EnvironmentHelper) {
  23941. return new BABYLON.EnvironmentHelper(options, this);
  23942. }
  23943. return null;
  23944. };
  23945. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23946. if (webVROptions === void 0) { webVROptions = {}; }
  23947. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23948. };
  23949. // Tags
  23950. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23951. if (tagsQuery === undefined) {
  23952. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23953. return list;
  23954. }
  23955. var listByTags = [];
  23956. forEach = forEach || (function (item) { return; });
  23957. for (var i in list) {
  23958. var item = list[i];
  23959. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23960. listByTags.push(item);
  23961. forEach(item);
  23962. }
  23963. }
  23964. return listByTags;
  23965. };
  23966. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23967. return this._getByTags(this.meshes, tagsQuery, forEach);
  23968. };
  23969. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23970. return this._getByTags(this.cameras, tagsQuery, forEach);
  23971. };
  23972. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23973. return this._getByTags(this.lights, tagsQuery, forEach);
  23974. };
  23975. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23976. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23977. };
  23978. /**
  23979. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23980. * This allowed control for front to back rendering or reversly depending of the special needs.
  23981. *
  23982. * @param renderingGroupId The rendering group id corresponding to its index
  23983. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23984. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23985. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23986. */
  23987. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23988. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23989. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23990. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23991. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23992. };
  23993. /**
  23994. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23995. *
  23996. * @param renderingGroupId The rendering group id corresponding to its index
  23997. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23998. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23999. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24000. */
  24001. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24002. if (depth === void 0) { depth = true; }
  24003. if (stencil === void 0) { stencil = true; }
  24004. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24005. };
  24006. /**
  24007. * Will flag all materials as dirty to trigger new shader compilation
  24008. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24009. */
  24010. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24011. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24012. var material = _a[_i];
  24013. if (predicate && !predicate(material)) {
  24014. continue;
  24015. }
  24016. material.markAsDirty(flag);
  24017. }
  24018. };
  24019. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24020. var _this = this;
  24021. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24022. this._activeRequests.push(request);
  24023. request.onCompleteObservable.add(function (request) {
  24024. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24025. });
  24026. return request;
  24027. };
  24028. /** @ignore */
  24029. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24030. var _this = this;
  24031. return new Promise(function (resolve, reject) {
  24032. _this._loadFile(url, function (data) {
  24033. resolve(data);
  24034. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24035. reject(exception);
  24036. });
  24037. });
  24038. };
  24039. // Statics
  24040. Scene._FOGMODE_NONE = 0;
  24041. Scene._FOGMODE_EXP = 1;
  24042. Scene._FOGMODE_EXP2 = 2;
  24043. Scene._FOGMODE_LINEAR = 3;
  24044. Scene._uniqueIdCounter = 0;
  24045. Scene.MinDeltaTime = 1.0;
  24046. Scene.MaxDeltaTime = 1000.0;
  24047. /** The distance in pixel that you have to move to prevent some events */
  24048. Scene.DragMovementThreshold = 10; // in pixels
  24049. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24050. Scene.LongPressDelay = 500; // in milliseconds
  24051. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24052. Scene.DoubleClickDelay = 300; // in milliseconds
  24053. /** If you need to check double click without raising a single click at first click, enable this flag */
  24054. Scene.ExclusiveDoubleClickMode = false;
  24055. return Scene;
  24056. }());
  24057. BABYLON.Scene = Scene;
  24058. })(BABYLON || (BABYLON = {}));
  24059. //# sourceMappingURL=babylon.scene.js.map
  24060. var BABYLON;
  24061. (function (BABYLON) {
  24062. /**
  24063. * Set of assets to keep when moving a scene into an asset container.
  24064. */
  24065. var KeepAssets = /** @class */ (function () {
  24066. function KeepAssets() {
  24067. /**
  24068. * Cameras to keep.
  24069. */
  24070. this.cameras = new Array();
  24071. /**
  24072. * Lights to keep.
  24073. */
  24074. this.lights = new Array();
  24075. /**
  24076. * Meshes to keep.
  24077. */
  24078. this.meshes = new Array();
  24079. /**
  24080. * Skeletons to keep.
  24081. */
  24082. this.skeletons = new Array();
  24083. /**
  24084. * ParticleSystems to keep.
  24085. */
  24086. this.particleSystems = new Array();
  24087. /**
  24088. * Animations to keep.
  24089. */
  24090. this.animations = new Array();
  24091. /**
  24092. * MultiMaterials to keep.
  24093. */
  24094. this.multiMaterials = new Array();
  24095. /**
  24096. * Materials to keep.
  24097. */
  24098. this.materials = new Array();
  24099. /**
  24100. * MorphTargetManagers to keep.
  24101. */
  24102. this.morphTargetManagers = new Array();
  24103. /**
  24104. * Geometries to keep.
  24105. */
  24106. this.geometries = new Array();
  24107. /**
  24108. * TransformNodes to keep.
  24109. */
  24110. this.transformNodes = new Array();
  24111. /**
  24112. * LensFlareSystems to keep.
  24113. */
  24114. this.lensFlareSystems = new Array();
  24115. /**
  24116. * ShadowGenerators to keep.
  24117. */
  24118. this.shadowGenerators = new Array();
  24119. /**
  24120. * ActionManagers to keep.
  24121. */
  24122. this.actionManagers = new Array();
  24123. /**
  24124. * Sounds to keep.
  24125. */
  24126. this.sounds = new Array();
  24127. }
  24128. return KeepAssets;
  24129. }());
  24130. BABYLON.KeepAssets = KeepAssets;
  24131. /**
  24132. * Container with a set of assets that can be added or removed from a scene.
  24133. */
  24134. var AssetContainer = /** @class */ (function () {
  24135. /**
  24136. * Instantiates an AssetContainer.
  24137. * @param scene The scene the AssetContainer belongs to.
  24138. */
  24139. function AssetContainer(scene) {
  24140. // Objects
  24141. /**
  24142. * Cameras populated in the container.
  24143. */
  24144. this.cameras = new Array();
  24145. /**
  24146. * Lights populated in the container.
  24147. */
  24148. this.lights = new Array();
  24149. /**
  24150. * Meshes populated in the container.
  24151. */
  24152. this.meshes = new Array();
  24153. /**
  24154. * Skeletons populated in the container.
  24155. */
  24156. this.skeletons = new Array();
  24157. /**
  24158. * ParticleSystems populated in the container.
  24159. */
  24160. this.particleSystems = new Array();
  24161. /**
  24162. * Animations populated in the container.
  24163. */
  24164. this.animations = new Array();
  24165. /**
  24166. * MultiMaterials populated in the container.
  24167. */
  24168. this.multiMaterials = new Array();
  24169. /**
  24170. * Materials populated in the container.
  24171. */
  24172. this.materials = new Array();
  24173. /**
  24174. * MorphTargetManagers populated in the container.
  24175. */
  24176. this.morphTargetManagers = new Array();
  24177. /**
  24178. * Geometries populated in the container.
  24179. */
  24180. this.geometries = new Array();
  24181. /**
  24182. * TransformNodes populated in the container.
  24183. */
  24184. this.transformNodes = new Array();
  24185. /**
  24186. * LensFlareSystems populated in the container.
  24187. */
  24188. this.lensFlareSystems = new Array();
  24189. /**
  24190. * ShadowGenerators populated in the container.
  24191. */
  24192. this.shadowGenerators = new Array();
  24193. /**
  24194. * ActionManagers populated in the container.
  24195. */
  24196. this.actionManagers = new Array();
  24197. /**
  24198. * Sounds populated in the container.
  24199. */
  24200. this.sounds = new Array();
  24201. this.scene = scene;
  24202. }
  24203. /**
  24204. * Adds all the assets from the container to the scene.
  24205. */
  24206. AssetContainer.prototype.addAllToScene = function () {
  24207. var _this = this;
  24208. this.cameras.forEach(function (o) {
  24209. _this.scene.addCamera(o);
  24210. });
  24211. this.lights.forEach(function (o) {
  24212. _this.scene.addLight(o);
  24213. });
  24214. this.meshes.forEach(function (o) {
  24215. _this.scene.addMesh(o);
  24216. });
  24217. this.skeletons.forEach(function (o) {
  24218. _this.scene.addSkeleton(o);
  24219. });
  24220. this.particleSystems.forEach(function (o) {
  24221. _this.scene.addParticleSystem(o);
  24222. });
  24223. this.animations.forEach(function (o) {
  24224. _this.scene.addAnimation(o);
  24225. });
  24226. this.multiMaterials.forEach(function (o) {
  24227. _this.scene.addMultiMaterial(o);
  24228. });
  24229. this.materials.forEach(function (o) {
  24230. _this.scene.addMaterial(o);
  24231. });
  24232. this.morphTargetManagers.forEach(function (o) {
  24233. _this.scene.addMorphTargetManager(o);
  24234. });
  24235. this.geometries.forEach(function (o) {
  24236. _this.scene.addGeometry(o);
  24237. });
  24238. this.transformNodes.forEach(function (o) {
  24239. _this.scene.addTransformNode(o);
  24240. });
  24241. this.lensFlareSystems.forEach(function (o) {
  24242. _this.scene.addLensFlareSystem(o);
  24243. });
  24244. this.actionManagers.forEach(function (o) {
  24245. _this.scene.addActionManager(o);
  24246. });
  24247. this.sounds.forEach(function (o) {
  24248. o.play();
  24249. o.autoplay = true;
  24250. _this.scene.mainSoundTrack.AddSound(o);
  24251. });
  24252. };
  24253. /**
  24254. * Removes all the assets in the container from the scene
  24255. */
  24256. AssetContainer.prototype.removeAllFromScene = function () {
  24257. var _this = this;
  24258. this.cameras.forEach(function (o) {
  24259. _this.scene.removeCamera(o);
  24260. });
  24261. this.lights.forEach(function (o) {
  24262. _this.scene.removeLight(o);
  24263. });
  24264. this.meshes.forEach(function (o) {
  24265. _this.scene.removeMesh(o);
  24266. });
  24267. this.skeletons.forEach(function (o) {
  24268. _this.scene.removeSkeleton(o);
  24269. });
  24270. this.particleSystems.forEach(function (o) {
  24271. _this.scene.removeParticleSystem(o);
  24272. });
  24273. this.animations.forEach(function (o) {
  24274. _this.scene.removeAnimation(o);
  24275. });
  24276. this.multiMaterials.forEach(function (o) {
  24277. _this.scene.removeMultiMaterial(o);
  24278. });
  24279. this.materials.forEach(function (o) {
  24280. _this.scene.removeMaterial(o);
  24281. });
  24282. this.morphTargetManagers.forEach(function (o) {
  24283. _this.scene.removeMorphTargetManager(o);
  24284. });
  24285. this.geometries.forEach(function (o) {
  24286. _this.scene.removeGeometry(o);
  24287. });
  24288. this.transformNodes.forEach(function (o) {
  24289. _this.scene.removeTransformNode(o);
  24290. });
  24291. this.lensFlareSystems.forEach(function (o) {
  24292. _this.scene.removeLensFlareSystem(o);
  24293. });
  24294. this.actionManagers.forEach(function (o) {
  24295. _this.scene.removeActionManager(o);
  24296. });
  24297. this.sounds.forEach(function (o) {
  24298. o.stop();
  24299. o.autoplay = false;
  24300. _this.scene.mainSoundTrack.RemoveSound(o);
  24301. });
  24302. };
  24303. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24304. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24305. var asset = sourceAssets_1[_i];
  24306. var move = true;
  24307. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24308. var keepAsset = keepAssets_1[_a];
  24309. if (asset === keepAsset) {
  24310. move = false;
  24311. break;
  24312. }
  24313. }
  24314. if (move) {
  24315. targetAssets.push(asset);
  24316. }
  24317. }
  24318. };
  24319. /**
  24320. * Removes all the assets contained in the scene and adds them to the container.
  24321. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24322. */
  24323. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24324. if (keepAssets === undefined) {
  24325. keepAssets = new KeepAssets();
  24326. }
  24327. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24328. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24329. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24330. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24331. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24332. Array.prototype.push.apply(this.animations, this.scene.animations);
  24333. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24334. Array.prototype.push.apply(this.lights, this.scene.lights);
  24335. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24336. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24337. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24338. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24339. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24340. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24341. this.removeAllFromScene();
  24342. };
  24343. return AssetContainer;
  24344. }());
  24345. BABYLON.AssetContainer = AssetContainer;
  24346. })(BABYLON || (BABYLON = {}));
  24347. //# sourceMappingURL=babylon.assetContainer.js.map
  24348. var BABYLON;
  24349. (function (BABYLON) {
  24350. var Buffer = /** @class */ (function () {
  24351. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24352. if (instanced === void 0) { instanced = false; }
  24353. if (engine instanceof BABYLON.Mesh) {
  24354. this._engine = engine.getScene().getEngine();
  24355. }
  24356. else {
  24357. this._engine = engine;
  24358. }
  24359. this._updatable = updatable;
  24360. this._data = data;
  24361. this._strideSize = stride;
  24362. if (!postponeInternalCreation) {
  24363. this.create();
  24364. }
  24365. this._instanced = instanced;
  24366. this._instanceDivisor = instanced ? 1 : 0;
  24367. }
  24368. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24369. // a lot of these parameters are ignored as they are overriden by the buffer
  24370. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24371. };
  24372. // Properties
  24373. Buffer.prototype.isUpdatable = function () {
  24374. return this._updatable;
  24375. };
  24376. Buffer.prototype.getData = function () {
  24377. return this._data;
  24378. };
  24379. Buffer.prototype.getBuffer = function () {
  24380. return this._buffer;
  24381. };
  24382. Buffer.prototype.getStrideSize = function () {
  24383. return this._strideSize;
  24384. };
  24385. Buffer.prototype.getIsInstanced = function () {
  24386. return this._instanced;
  24387. };
  24388. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24389. get: function () {
  24390. return this._instanceDivisor;
  24391. },
  24392. set: function (value) {
  24393. this._instanceDivisor = value;
  24394. if (value == 0) {
  24395. this._instanced = false;
  24396. }
  24397. else {
  24398. this._instanced = true;
  24399. }
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. // Methods
  24405. Buffer.prototype.create = function (data) {
  24406. if (data === void 0) { data = null; }
  24407. if (!data && this._buffer) {
  24408. return; // nothing to do
  24409. }
  24410. data = data || this._data;
  24411. if (!data) {
  24412. return;
  24413. }
  24414. if (!this._buffer) {
  24415. if (this._updatable) {
  24416. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24417. this._data = data;
  24418. }
  24419. else {
  24420. this._buffer = this._engine.createVertexBuffer(data);
  24421. }
  24422. }
  24423. else if (this._updatable) {
  24424. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24425. this._data = data;
  24426. }
  24427. };
  24428. Buffer.prototype._rebuild = function () {
  24429. this._buffer = null;
  24430. this.create(this._data);
  24431. };
  24432. Buffer.prototype.update = function (data) {
  24433. this.create(data);
  24434. };
  24435. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24436. if (!this._buffer) {
  24437. return;
  24438. }
  24439. if (this._updatable) {
  24440. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24441. this._data = null;
  24442. }
  24443. };
  24444. Buffer.prototype.dispose = function () {
  24445. if (!this._buffer) {
  24446. return;
  24447. }
  24448. if (this._engine._releaseBuffer(this._buffer)) {
  24449. this._buffer = null;
  24450. }
  24451. };
  24452. return Buffer;
  24453. }());
  24454. BABYLON.Buffer = Buffer;
  24455. })(BABYLON || (BABYLON = {}));
  24456. //# sourceMappingURL=babylon.buffer.js.map
  24457. var BABYLON;
  24458. (function (BABYLON) {
  24459. var VertexBuffer = /** @class */ (function () {
  24460. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24461. if (!stride) {
  24462. // Deduce stride from kind
  24463. switch (kind) {
  24464. case VertexBuffer.PositionKind:
  24465. stride = 3;
  24466. break;
  24467. case VertexBuffer.NormalKind:
  24468. stride = 3;
  24469. break;
  24470. case VertexBuffer.UVKind:
  24471. case VertexBuffer.UV2Kind:
  24472. case VertexBuffer.UV3Kind:
  24473. case VertexBuffer.UV4Kind:
  24474. case VertexBuffer.UV5Kind:
  24475. case VertexBuffer.UV6Kind:
  24476. stride = 2;
  24477. break;
  24478. case VertexBuffer.TangentKind:
  24479. case VertexBuffer.ColorKind:
  24480. stride = 4;
  24481. break;
  24482. case VertexBuffer.MatricesIndicesKind:
  24483. case VertexBuffer.MatricesIndicesExtraKind:
  24484. stride = 4;
  24485. break;
  24486. case VertexBuffer.MatricesWeightsKind:
  24487. case VertexBuffer.MatricesWeightsExtraKind:
  24488. default:
  24489. stride = 4;
  24490. break;
  24491. }
  24492. }
  24493. if (data instanceof BABYLON.Buffer) {
  24494. if (!stride) {
  24495. stride = data.getStrideSize();
  24496. }
  24497. this._buffer = data;
  24498. this._ownsBuffer = false;
  24499. }
  24500. else {
  24501. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24502. this._ownsBuffer = true;
  24503. }
  24504. this._stride = stride;
  24505. this._offset = offset ? offset : 0;
  24506. this._size = size ? size : stride;
  24507. this._kind = kind;
  24508. }
  24509. VertexBuffer.prototype._rebuild = function () {
  24510. if (!this._buffer) {
  24511. return;
  24512. }
  24513. this._buffer._rebuild();
  24514. };
  24515. /**
  24516. * Returns the kind of the VertexBuffer (string).
  24517. */
  24518. VertexBuffer.prototype.getKind = function () {
  24519. return this._kind;
  24520. };
  24521. // Properties
  24522. /**
  24523. * Boolean : is the VertexBuffer updatable ?
  24524. */
  24525. VertexBuffer.prototype.isUpdatable = function () {
  24526. return this._buffer.isUpdatable();
  24527. };
  24528. /**
  24529. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24530. */
  24531. VertexBuffer.prototype.getData = function () {
  24532. return this._buffer.getData();
  24533. };
  24534. /**
  24535. * Returns the WebGLBuffer associated to the VertexBuffer.
  24536. */
  24537. VertexBuffer.prototype.getBuffer = function () {
  24538. return this._buffer.getBuffer();
  24539. };
  24540. /**
  24541. * Returns the stride of the VertexBuffer (integer).
  24542. */
  24543. VertexBuffer.prototype.getStrideSize = function () {
  24544. return this._stride;
  24545. };
  24546. /**
  24547. * Returns the offset (integer).
  24548. */
  24549. VertexBuffer.prototype.getOffset = function () {
  24550. return this._offset;
  24551. };
  24552. /**
  24553. * Returns the VertexBuffer total size (integer).
  24554. */
  24555. VertexBuffer.prototype.getSize = function () {
  24556. return this._size;
  24557. };
  24558. /**
  24559. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24560. */
  24561. VertexBuffer.prototype.getIsInstanced = function () {
  24562. return this._buffer.getIsInstanced();
  24563. };
  24564. /**
  24565. * Returns the instancing divisor, zero for non-instanced (integer).
  24566. */
  24567. VertexBuffer.prototype.getInstanceDivisor = function () {
  24568. return this._buffer.instanceDivisor;
  24569. };
  24570. // Methods
  24571. /**
  24572. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24573. * Returns the created WebGLBuffer.
  24574. */
  24575. VertexBuffer.prototype.create = function (data) {
  24576. return this._buffer.create(data);
  24577. };
  24578. /**
  24579. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24580. * This function will create a new buffer if the current one is not updatable
  24581. * Returns the updated WebGLBuffer.
  24582. */
  24583. VertexBuffer.prototype.update = function (data) {
  24584. return this._buffer.update(data);
  24585. };
  24586. /**
  24587. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24588. * Returns the directly updated WebGLBuffer.
  24589. */
  24590. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24591. return this._buffer.updateDirectly(data, offset);
  24592. };
  24593. /**
  24594. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24595. */
  24596. VertexBuffer.prototype.dispose = function () {
  24597. if (this._ownsBuffer) {
  24598. this._buffer.dispose();
  24599. }
  24600. };
  24601. Object.defineProperty(VertexBuffer, "PositionKind", {
  24602. get: function () {
  24603. return VertexBuffer._PositionKind;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(VertexBuffer, "NormalKind", {
  24609. get: function () {
  24610. return VertexBuffer._NormalKind;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(VertexBuffer, "TangentKind", {
  24616. get: function () {
  24617. return VertexBuffer._TangentKind;
  24618. },
  24619. enumerable: true,
  24620. configurable: true
  24621. });
  24622. Object.defineProperty(VertexBuffer, "UVKind", {
  24623. get: function () {
  24624. return VertexBuffer._UVKind;
  24625. },
  24626. enumerable: true,
  24627. configurable: true
  24628. });
  24629. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24630. get: function () {
  24631. return VertexBuffer._UV2Kind;
  24632. },
  24633. enumerable: true,
  24634. configurable: true
  24635. });
  24636. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24637. get: function () {
  24638. return VertexBuffer._UV3Kind;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24644. get: function () {
  24645. return VertexBuffer._UV4Kind;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24651. get: function () {
  24652. return VertexBuffer._UV5Kind;
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24658. get: function () {
  24659. return VertexBuffer._UV6Kind;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. Object.defineProperty(VertexBuffer, "ColorKind", {
  24665. get: function () {
  24666. return VertexBuffer._ColorKind;
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24672. get: function () {
  24673. return VertexBuffer._MatricesIndicesKind;
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24679. get: function () {
  24680. return VertexBuffer._MatricesWeightsKind;
  24681. },
  24682. enumerable: true,
  24683. configurable: true
  24684. });
  24685. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24686. get: function () {
  24687. return VertexBuffer._MatricesIndicesExtraKind;
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24693. get: function () {
  24694. return VertexBuffer._MatricesWeightsExtraKind;
  24695. },
  24696. enumerable: true,
  24697. configurable: true
  24698. });
  24699. // Enums
  24700. VertexBuffer._PositionKind = "position";
  24701. VertexBuffer._NormalKind = "normal";
  24702. VertexBuffer._TangentKind = "tangent";
  24703. VertexBuffer._UVKind = "uv";
  24704. VertexBuffer._UV2Kind = "uv2";
  24705. VertexBuffer._UV3Kind = "uv3";
  24706. VertexBuffer._UV4Kind = "uv4";
  24707. VertexBuffer._UV5Kind = "uv5";
  24708. VertexBuffer._UV6Kind = "uv6";
  24709. VertexBuffer._ColorKind = "color";
  24710. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24711. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24712. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24713. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24714. return VertexBuffer;
  24715. }());
  24716. BABYLON.VertexBuffer = VertexBuffer;
  24717. })(BABYLON || (BABYLON = {}));
  24718. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24719. var BABYLON;
  24720. (function (BABYLON) {
  24721. /**
  24722. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24723. */
  24724. var DummyInternalTextureTracker = /** @class */ (function () {
  24725. function DummyInternalTextureTracker() {
  24726. /**
  24727. * Gets or set the previous tracker in the list
  24728. */
  24729. this.previous = null;
  24730. /**
  24731. * Gets or set the next tracker in the list
  24732. */
  24733. this.next = null;
  24734. }
  24735. return DummyInternalTextureTracker;
  24736. }());
  24737. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24738. })(BABYLON || (BABYLON = {}));
  24739. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24740. var BABYLON;
  24741. (function (BABYLON) {
  24742. /**
  24743. * Class used to store data associated with WebGL texture data for the engine
  24744. * This class should not be used directly
  24745. */
  24746. var InternalTexture = /** @class */ (function () {
  24747. /**
  24748. * Creates a new InternalTexture
  24749. * @param engine defines the engine to use
  24750. * @param dataSource defines the type of data that will be used
  24751. */
  24752. function InternalTexture(engine, dataSource) {
  24753. /**
  24754. * Observable called when the texture is loaded
  24755. */
  24756. this.onLoadedObservable = new BABYLON.Observable();
  24757. /**
  24758. * Gets or set the previous tracker in the list
  24759. */
  24760. this.previous = null;
  24761. /**
  24762. * Gets or set the next tracker in the list
  24763. */
  24764. this.next = null;
  24765. // Private
  24766. /** @ignore */
  24767. this._initialSlot = -1;
  24768. /** @ignore */
  24769. this._designatedSlot = -1;
  24770. /** @ignore */
  24771. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24772. /** @ignore */
  24773. this._references = 1;
  24774. this._engine = engine;
  24775. this._dataSource = dataSource;
  24776. this._webGLTexture = engine._createTexture();
  24777. }
  24778. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24779. /**
  24780. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24781. */
  24782. get: function () {
  24783. return this._dataSource;
  24784. },
  24785. enumerable: true,
  24786. configurable: true
  24787. });
  24788. /**
  24789. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24790. */
  24791. InternalTexture.prototype.incrementReferences = function () {
  24792. this._references++;
  24793. };
  24794. /**
  24795. * Change the size of the texture (not the size of the content)
  24796. * @param width defines the new width
  24797. * @param height defines the new height
  24798. * @param depth defines the new depth (1 by default)
  24799. */
  24800. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24801. if (depth === void 0) { depth = 1; }
  24802. this.width = width;
  24803. this.height = height;
  24804. this.depth = depth;
  24805. this.baseWidth = width;
  24806. this.baseHeight = height;
  24807. this.baseDepth = depth;
  24808. this._size = width * height * depth;
  24809. };
  24810. /** @ignore */
  24811. InternalTexture.prototype._rebuild = function () {
  24812. var _this = this;
  24813. var proxy;
  24814. this.isReady = false;
  24815. this._cachedCoordinatesMode = null;
  24816. this._cachedWrapU = null;
  24817. this._cachedWrapV = null;
  24818. this._cachedAnisotropicFilteringLevel = null;
  24819. switch (this._dataSource) {
  24820. case InternalTexture.DATASOURCE_TEMP:
  24821. return;
  24822. case InternalTexture.DATASOURCE_URL:
  24823. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24824. _this.isReady = true;
  24825. }, null, this._buffer, undefined, this.format);
  24826. proxy._swapAndDie(this);
  24827. return;
  24828. case InternalTexture.DATASOURCE_RAW:
  24829. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24830. proxy._swapAndDie(this);
  24831. this.isReady = true;
  24832. return;
  24833. case InternalTexture.DATASOURCE_RAW3D:
  24834. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24835. proxy._swapAndDie(this);
  24836. this.isReady = true;
  24837. return;
  24838. case InternalTexture.DATASOURCE_DYNAMIC:
  24839. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24840. proxy._swapAndDie(this);
  24841. // The engine will make sure to update content so no need to flag it as isReady = true
  24842. return;
  24843. case InternalTexture.DATASOURCE_RENDERTARGET:
  24844. var options = new BABYLON.RenderTargetCreationOptions();
  24845. options.generateDepthBuffer = this._generateDepthBuffer;
  24846. options.generateMipMaps = this.generateMipMaps;
  24847. options.generateStencilBuffer = this._generateStencilBuffer;
  24848. options.samplingMode = this.samplingMode;
  24849. options.type = this.type;
  24850. if (this.isCube) {
  24851. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24852. }
  24853. else {
  24854. var size = {
  24855. width: this.width,
  24856. height: this.height
  24857. };
  24858. proxy = this._engine.createRenderTargetTexture(size, options);
  24859. }
  24860. proxy._swapAndDie(this);
  24861. this.isReady = true;
  24862. return;
  24863. case InternalTexture.DATASOURCE_CUBE:
  24864. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24865. _this.isReady = true;
  24866. }, null, this.format, this._extension);
  24867. proxy._swapAndDie(this);
  24868. return;
  24869. case InternalTexture.DATASOURCE_CUBERAW:
  24870. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24871. proxy._swapAndDie(this);
  24872. this.isReady = true;
  24873. return;
  24874. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24875. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24876. if (proxy) {
  24877. proxy._swapAndDie(_this);
  24878. }
  24879. _this.isReady = true;
  24880. }, null, this.format, this._extension);
  24881. return;
  24882. }
  24883. };
  24884. InternalTexture.prototype._swapAndDie = function (target) {
  24885. target._webGLTexture = this._webGLTexture;
  24886. if (this._framebuffer) {
  24887. target._framebuffer = this._framebuffer;
  24888. }
  24889. if (this._depthStencilBuffer) {
  24890. target._depthStencilBuffer = this._depthStencilBuffer;
  24891. }
  24892. if (this._lodTextureHigh) {
  24893. if (target._lodTextureHigh) {
  24894. target._lodTextureHigh.dispose();
  24895. }
  24896. target._lodTextureHigh = this._lodTextureHigh;
  24897. }
  24898. if (this._lodTextureMid) {
  24899. if (target._lodTextureMid) {
  24900. target._lodTextureMid.dispose();
  24901. }
  24902. target._lodTextureMid = this._lodTextureMid;
  24903. }
  24904. if (this._lodTextureLow) {
  24905. if (target._lodTextureLow) {
  24906. target._lodTextureLow.dispose();
  24907. }
  24908. target._lodTextureLow = this._lodTextureLow;
  24909. }
  24910. var cache = this._engine.getLoadedTexturesCache();
  24911. var index = cache.indexOf(this);
  24912. if (index !== -1) {
  24913. cache.splice(index, 1);
  24914. }
  24915. };
  24916. /**
  24917. * Dispose the current allocated resources
  24918. */
  24919. InternalTexture.prototype.dispose = function () {
  24920. if (!this._webGLTexture) {
  24921. return;
  24922. }
  24923. this._references--;
  24924. if (this._references === 0) {
  24925. this._engine._releaseTexture(this);
  24926. this._webGLTexture = null;
  24927. this.previous = null;
  24928. this.next = null;
  24929. }
  24930. };
  24931. /**
  24932. * The source of the texture data is unknown
  24933. */
  24934. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24935. /**
  24936. * Texture data comes from an URL
  24937. */
  24938. InternalTexture.DATASOURCE_URL = 1;
  24939. /**
  24940. * Texture data is only used for temporary storage
  24941. */
  24942. InternalTexture.DATASOURCE_TEMP = 2;
  24943. /**
  24944. * Texture data comes from raw data (ArrayBuffer)
  24945. */
  24946. InternalTexture.DATASOURCE_RAW = 3;
  24947. /**
  24948. * Texture content is dynamic (video or dynamic texture)
  24949. */
  24950. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24951. /**
  24952. * Texture content is generated by rendering to it
  24953. */
  24954. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24955. /**
  24956. * Texture content is part of a multi render target process
  24957. */
  24958. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24959. /**
  24960. * Texture data comes from a cube data file
  24961. */
  24962. InternalTexture.DATASOURCE_CUBE = 7;
  24963. /**
  24964. * Texture data comes from a raw cube data
  24965. */
  24966. InternalTexture.DATASOURCE_CUBERAW = 8;
  24967. /**
  24968. * Texture data come from a prefiltered cube data file
  24969. */
  24970. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24971. /**
  24972. * Texture content is raw 3D data
  24973. */
  24974. InternalTexture.DATASOURCE_RAW3D = 10;
  24975. return InternalTexture;
  24976. }());
  24977. BABYLON.InternalTexture = InternalTexture;
  24978. })(BABYLON || (BABYLON = {}));
  24979. //# sourceMappingURL=babylon.internalTexture.js.map
  24980. var BABYLON;
  24981. (function (BABYLON) {
  24982. var BaseTexture = /** @class */ (function () {
  24983. function BaseTexture(scene) {
  24984. this._hasAlpha = false;
  24985. this.getAlphaFromRGB = false;
  24986. this.level = 1;
  24987. this.coordinatesIndex = 0;
  24988. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24989. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24990. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24991. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24992. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24993. this.isCube = false;
  24994. this.is3D = false;
  24995. this.gammaSpace = true;
  24996. this.invertZ = false;
  24997. this.lodLevelInAlpha = false;
  24998. this.lodGenerationOffset = 0.0;
  24999. this.lodGenerationScale = 0.8;
  25000. this.isRenderTarget = false;
  25001. this.animations = new Array();
  25002. /**
  25003. * An event triggered when the texture is disposed.
  25004. * @type {BABYLON.Observable}
  25005. */
  25006. this.onDisposeObservable = new BABYLON.Observable();
  25007. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25008. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25009. if (this._scene) {
  25010. this._scene.textures.push(this);
  25011. }
  25012. this._uid = null;
  25013. }
  25014. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25015. get: function () {
  25016. return this._hasAlpha;
  25017. },
  25018. set: function (value) {
  25019. if (this._hasAlpha === value) {
  25020. return;
  25021. }
  25022. this._hasAlpha = value;
  25023. if (this._scene) {
  25024. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25025. }
  25026. },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25031. get: function () {
  25032. return this._coordinatesMode;
  25033. },
  25034. set: function (value) {
  25035. if (this._coordinatesMode === value) {
  25036. return;
  25037. }
  25038. this._coordinatesMode = value;
  25039. if (this._scene) {
  25040. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25041. }
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. Object.defineProperty(BaseTexture.prototype, "uid", {
  25047. get: function () {
  25048. if (!this._uid) {
  25049. this._uid = BABYLON.Tools.RandomId();
  25050. }
  25051. return this._uid;
  25052. },
  25053. enumerable: true,
  25054. configurable: true
  25055. });
  25056. BaseTexture.prototype.toString = function () {
  25057. return this.name;
  25058. };
  25059. BaseTexture.prototype.getClassName = function () {
  25060. return "BaseTexture";
  25061. };
  25062. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25063. set: function (callback) {
  25064. if (this._onDisposeObserver) {
  25065. this.onDisposeObservable.remove(this._onDisposeObserver);
  25066. }
  25067. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25068. },
  25069. enumerable: true,
  25070. configurable: true
  25071. });
  25072. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25073. get: function () {
  25074. return true;
  25075. },
  25076. enumerable: true,
  25077. configurable: true
  25078. });
  25079. BaseTexture.prototype.getScene = function () {
  25080. return this._scene;
  25081. };
  25082. BaseTexture.prototype.getTextureMatrix = function () {
  25083. return BABYLON.Matrix.IdentityReadOnly;
  25084. };
  25085. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25086. return BABYLON.Matrix.IdentityReadOnly;
  25087. };
  25088. BaseTexture.prototype.getInternalTexture = function () {
  25089. return this._texture;
  25090. };
  25091. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25092. return !this.isBlocking || this.isReady();
  25093. };
  25094. BaseTexture.prototype.isReady = function () {
  25095. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25096. this.delayLoad();
  25097. return false;
  25098. }
  25099. if (this._texture) {
  25100. return this._texture.isReady;
  25101. }
  25102. return false;
  25103. };
  25104. BaseTexture.prototype.getSize = function () {
  25105. if (this._texture && this._texture.width) {
  25106. return new BABYLON.Size(this._texture.width, this._texture.height);
  25107. }
  25108. if (this._texture && this._texture._size) {
  25109. return new BABYLON.Size(this._texture._size, this._texture._size);
  25110. }
  25111. return BABYLON.Size.Zero();
  25112. };
  25113. BaseTexture.prototype.getBaseSize = function () {
  25114. if (!this.isReady() || !this._texture)
  25115. return BABYLON.Size.Zero();
  25116. if (this._texture._size) {
  25117. return new BABYLON.Size(this._texture._size, this._texture._size);
  25118. }
  25119. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25120. };
  25121. BaseTexture.prototype.scale = function (ratio) {
  25122. };
  25123. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25124. get: function () {
  25125. return false;
  25126. },
  25127. enumerable: true,
  25128. configurable: true
  25129. });
  25130. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25131. if (!this._scene) {
  25132. return null;
  25133. }
  25134. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25135. for (var index = 0; index < texturesCache.length; index++) {
  25136. var texturesCacheEntry = texturesCache[index];
  25137. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25138. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25139. texturesCacheEntry.incrementReferences();
  25140. return texturesCacheEntry;
  25141. }
  25142. }
  25143. }
  25144. return null;
  25145. };
  25146. BaseTexture.prototype._rebuild = function () {
  25147. };
  25148. BaseTexture.prototype.delayLoad = function () {
  25149. };
  25150. BaseTexture.prototype.clone = function () {
  25151. return null;
  25152. };
  25153. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25154. get: function () {
  25155. if (!this._texture) {
  25156. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25157. }
  25158. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25159. },
  25160. enumerable: true,
  25161. configurable: true
  25162. });
  25163. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25164. get: function () {
  25165. if (!this._texture) {
  25166. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25167. }
  25168. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. BaseTexture.prototype.readPixels = function (faceIndex) {
  25174. if (faceIndex === void 0) { faceIndex = 0; }
  25175. if (!this._texture) {
  25176. return null;
  25177. }
  25178. var size = this.getSize();
  25179. var scene = this.getScene();
  25180. if (!scene) {
  25181. return null;
  25182. }
  25183. var engine = scene.getEngine();
  25184. if (this._texture.isCube) {
  25185. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25186. }
  25187. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25188. };
  25189. BaseTexture.prototype.releaseInternalTexture = function () {
  25190. if (this._texture) {
  25191. this._texture.dispose();
  25192. this._texture = null;
  25193. }
  25194. };
  25195. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25196. get: function () {
  25197. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25198. return null;
  25199. }
  25200. if (!this._texture._sphericalPolynomial) {
  25201. this._texture._sphericalPolynomial =
  25202. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25203. }
  25204. return this._texture._sphericalPolynomial;
  25205. },
  25206. set: function (value) {
  25207. if (this._texture) {
  25208. this._texture._sphericalPolynomial = value;
  25209. }
  25210. },
  25211. enumerable: true,
  25212. configurable: true
  25213. });
  25214. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25215. get: function () {
  25216. if (this._texture) {
  25217. return this._texture._lodTextureHigh;
  25218. }
  25219. return null;
  25220. },
  25221. enumerable: true,
  25222. configurable: true
  25223. });
  25224. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25225. get: function () {
  25226. if (this._texture) {
  25227. return this._texture._lodTextureMid;
  25228. }
  25229. return null;
  25230. },
  25231. enumerable: true,
  25232. configurable: true
  25233. });
  25234. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25235. get: function () {
  25236. if (this._texture) {
  25237. return this._texture._lodTextureLow;
  25238. }
  25239. return null;
  25240. },
  25241. enumerable: true,
  25242. configurable: true
  25243. });
  25244. BaseTexture.prototype.dispose = function () {
  25245. if (!this._scene) {
  25246. return;
  25247. }
  25248. // Animations
  25249. this._scene.stopAnimation(this);
  25250. // Remove from scene
  25251. this._scene._removePendingData(this);
  25252. var index = this._scene.textures.indexOf(this);
  25253. if (index >= 0) {
  25254. this._scene.textures.splice(index, 1);
  25255. }
  25256. if (this._texture === undefined) {
  25257. return;
  25258. }
  25259. // Release
  25260. this.releaseInternalTexture();
  25261. // Callback
  25262. this.onDisposeObservable.notifyObservers(this);
  25263. this.onDisposeObservable.clear();
  25264. };
  25265. BaseTexture.prototype.serialize = function () {
  25266. if (!this.name) {
  25267. return null;
  25268. }
  25269. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25270. // Animations
  25271. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25272. return serializationObject;
  25273. };
  25274. BaseTexture.WhenAllReady = function (textures, callback) {
  25275. var numRemaining = textures.length;
  25276. if (numRemaining === 0) {
  25277. callback();
  25278. return;
  25279. }
  25280. var _loop_1 = function () {
  25281. texture = textures[i];
  25282. if (texture.isReady()) {
  25283. if (--numRemaining === 0) {
  25284. callback();
  25285. }
  25286. }
  25287. else {
  25288. onLoadObservable = texture.onLoadObservable;
  25289. var onLoadCallback_1 = function () {
  25290. onLoadObservable.removeCallback(onLoadCallback_1);
  25291. if (--numRemaining === 0) {
  25292. callback();
  25293. }
  25294. };
  25295. onLoadObservable.add(onLoadCallback_1);
  25296. }
  25297. };
  25298. var texture, onLoadObservable;
  25299. for (var i = 0; i < textures.length; i++) {
  25300. _loop_1();
  25301. }
  25302. };
  25303. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25304. __decorate([
  25305. BABYLON.serialize()
  25306. ], BaseTexture.prototype, "name", void 0);
  25307. __decorate([
  25308. BABYLON.serialize("hasAlpha")
  25309. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25310. __decorate([
  25311. BABYLON.serialize()
  25312. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25313. __decorate([
  25314. BABYLON.serialize()
  25315. ], BaseTexture.prototype, "level", void 0);
  25316. __decorate([
  25317. BABYLON.serialize()
  25318. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25319. __decorate([
  25320. BABYLON.serialize("coordinatesMode")
  25321. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25322. __decorate([
  25323. BABYLON.serialize()
  25324. ], BaseTexture.prototype, "wrapU", void 0);
  25325. __decorate([
  25326. BABYLON.serialize()
  25327. ], BaseTexture.prototype, "wrapV", void 0);
  25328. __decorate([
  25329. BABYLON.serialize()
  25330. ], BaseTexture.prototype, "wrapR", void 0);
  25331. __decorate([
  25332. BABYLON.serialize()
  25333. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25334. __decorate([
  25335. BABYLON.serialize()
  25336. ], BaseTexture.prototype, "isCube", void 0);
  25337. __decorate([
  25338. BABYLON.serialize()
  25339. ], BaseTexture.prototype, "is3D", void 0);
  25340. __decorate([
  25341. BABYLON.serialize()
  25342. ], BaseTexture.prototype, "gammaSpace", void 0);
  25343. __decorate([
  25344. BABYLON.serialize()
  25345. ], BaseTexture.prototype, "invertZ", void 0);
  25346. __decorate([
  25347. BABYLON.serialize()
  25348. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25349. __decorate([
  25350. BABYLON.serialize()
  25351. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25352. __decorate([
  25353. BABYLON.serialize()
  25354. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25355. __decorate([
  25356. BABYLON.serialize()
  25357. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25358. return BaseTexture;
  25359. }());
  25360. BABYLON.BaseTexture = BaseTexture;
  25361. })(BABYLON || (BABYLON = {}));
  25362. //# sourceMappingURL=babylon.baseTexture.js.map
  25363. var BABYLON;
  25364. (function (BABYLON) {
  25365. var Texture = /** @class */ (function (_super) {
  25366. __extends(Texture, _super);
  25367. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25368. if (noMipmap === void 0) { noMipmap = false; }
  25369. if (invertY === void 0) { invertY = true; }
  25370. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25371. if (onLoad === void 0) { onLoad = null; }
  25372. if (onError === void 0) { onError = null; }
  25373. if (buffer === void 0) { buffer = null; }
  25374. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25375. var _this = _super.call(this, scene) || this;
  25376. _this.uOffset = 0;
  25377. _this.vOffset = 0;
  25378. _this.uScale = 1.0;
  25379. _this.vScale = 1.0;
  25380. _this.uAng = 0;
  25381. _this.vAng = 0;
  25382. _this.wAng = 0;
  25383. _this._isBlocking = true;
  25384. _this.name = url || "";
  25385. _this.url = url;
  25386. _this._noMipmap = noMipmap;
  25387. _this._invertY = invertY;
  25388. _this._samplingMode = samplingMode;
  25389. _this._buffer = buffer;
  25390. _this._deleteBuffer = deleteBuffer;
  25391. if (format) {
  25392. _this._format = format;
  25393. }
  25394. scene = _this.getScene();
  25395. if (!scene) {
  25396. return _this;
  25397. }
  25398. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25399. var load = function () {
  25400. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25401. _this.onLoadObservable.notifyObservers(_this);
  25402. }
  25403. if (onLoad) {
  25404. onLoad();
  25405. }
  25406. if (!_this.isBlocking && scene) {
  25407. scene.resetCachedMaterial();
  25408. }
  25409. };
  25410. if (!_this.url) {
  25411. _this._delayedOnLoad = load;
  25412. _this._delayedOnError = onError;
  25413. return _this;
  25414. }
  25415. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25416. if (!_this._texture) {
  25417. if (!scene.useDelayedTextureLoading) {
  25418. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25419. if (deleteBuffer) {
  25420. delete _this._buffer;
  25421. }
  25422. }
  25423. else {
  25424. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25425. _this._delayedOnLoad = load;
  25426. _this._delayedOnError = onError;
  25427. }
  25428. }
  25429. else {
  25430. if (_this._texture.isReady) {
  25431. BABYLON.Tools.SetImmediate(function () { return load(); });
  25432. }
  25433. else {
  25434. _this._texture.onLoadedObservable.add(load);
  25435. }
  25436. }
  25437. return _this;
  25438. }
  25439. Object.defineProperty(Texture.prototype, "noMipmap", {
  25440. get: function () {
  25441. return this._noMipmap;
  25442. },
  25443. enumerable: true,
  25444. configurable: true
  25445. });
  25446. Object.defineProperty(Texture.prototype, "isBlocking", {
  25447. get: function () {
  25448. return this._isBlocking;
  25449. },
  25450. set: function (value) {
  25451. this._isBlocking = value;
  25452. },
  25453. enumerable: true,
  25454. configurable: true
  25455. });
  25456. Object.defineProperty(Texture.prototype, "samplingMode", {
  25457. get: function () {
  25458. return this._samplingMode;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. Texture.prototype.updateURL = function (url) {
  25464. this.url = url;
  25465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25466. this.delayLoad();
  25467. };
  25468. Texture.prototype.delayLoad = function () {
  25469. var _this = this;
  25470. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25471. return;
  25472. }
  25473. var scene = this.getScene();
  25474. if (!scene) {
  25475. return;
  25476. }
  25477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25478. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25479. if (!this._texture) {
  25480. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25481. if (this._deleteBuffer) {
  25482. delete this._buffer;
  25483. }
  25484. }
  25485. else {
  25486. if (this._texture.isReady) {
  25487. BABYLON.Tools.SetImmediate(function () {
  25488. if (!_this._delayedOnLoad) {
  25489. return;
  25490. }
  25491. _this._delayedOnLoad();
  25492. });
  25493. }
  25494. else {
  25495. if (this._delayedOnLoad) {
  25496. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25497. }
  25498. }
  25499. }
  25500. };
  25501. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25502. if (!this._texture) {
  25503. return;
  25504. }
  25505. var scene = this.getScene();
  25506. if (!scene) {
  25507. return;
  25508. }
  25509. this._samplingMode = samplingMode;
  25510. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25511. };
  25512. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25513. x *= this.uScale;
  25514. y *= this.vScale;
  25515. x -= 0.5 * this.uScale;
  25516. y -= 0.5 * this.vScale;
  25517. z -= 0.5;
  25518. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25519. t.x += 0.5 * this.uScale + this.uOffset;
  25520. t.y += 0.5 * this.vScale + this.vOffset;
  25521. t.z += 0.5;
  25522. };
  25523. Texture.prototype.getTextureMatrix = function () {
  25524. var _this = this;
  25525. if (this.uOffset === this._cachedUOffset &&
  25526. this.vOffset === this._cachedVOffset &&
  25527. this.uScale === this._cachedUScale &&
  25528. this.vScale === this._cachedVScale &&
  25529. this.uAng === this._cachedUAng &&
  25530. this.vAng === this._cachedVAng &&
  25531. this.wAng === this._cachedWAng) {
  25532. return this._cachedTextureMatrix;
  25533. }
  25534. this._cachedUOffset = this.uOffset;
  25535. this._cachedVOffset = this.vOffset;
  25536. this._cachedUScale = this.uScale;
  25537. this._cachedVScale = this.vScale;
  25538. this._cachedUAng = this.uAng;
  25539. this._cachedVAng = this.vAng;
  25540. this._cachedWAng = this.wAng;
  25541. if (!this._cachedTextureMatrix) {
  25542. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25543. this._rowGenerationMatrix = new BABYLON.Matrix();
  25544. this._t0 = BABYLON.Vector3.Zero();
  25545. this._t1 = BABYLON.Vector3.Zero();
  25546. this._t2 = BABYLON.Vector3.Zero();
  25547. }
  25548. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25549. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25550. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25551. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25552. this._t1.subtractInPlace(this._t0);
  25553. this._t2.subtractInPlace(this._t0);
  25554. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25555. this._cachedTextureMatrix.m[0] = this._t1.x;
  25556. this._cachedTextureMatrix.m[1] = this._t1.y;
  25557. this._cachedTextureMatrix.m[2] = this._t1.z;
  25558. this._cachedTextureMatrix.m[4] = this._t2.x;
  25559. this._cachedTextureMatrix.m[5] = this._t2.y;
  25560. this._cachedTextureMatrix.m[6] = this._t2.z;
  25561. this._cachedTextureMatrix.m[8] = this._t0.x;
  25562. this._cachedTextureMatrix.m[9] = this._t0.y;
  25563. this._cachedTextureMatrix.m[10] = this._t0.z;
  25564. var scene = this.getScene();
  25565. if (!scene) {
  25566. return this._cachedTextureMatrix;
  25567. }
  25568. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25569. return mat.hasTexture(_this);
  25570. });
  25571. return this._cachedTextureMatrix;
  25572. };
  25573. Texture.prototype.getReflectionTextureMatrix = function () {
  25574. var _this = this;
  25575. var scene = this.getScene();
  25576. if (!scene) {
  25577. return this._cachedTextureMatrix;
  25578. }
  25579. if (this.uOffset === this._cachedUOffset &&
  25580. this.vOffset === this._cachedVOffset &&
  25581. this.uScale === this._cachedUScale &&
  25582. this.vScale === this._cachedVScale &&
  25583. this.coordinatesMode === this._cachedCoordinatesMode) {
  25584. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25585. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25586. return this._cachedTextureMatrix;
  25587. }
  25588. }
  25589. else {
  25590. return this._cachedTextureMatrix;
  25591. }
  25592. }
  25593. if (!this._cachedTextureMatrix) {
  25594. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25595. }
  25596. if (!this._projectionModeMatrix) {
  25597. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25598. }
  25599. this._cachedUOffset = this.uOffset;
  25600. this._cachedVOffset = this.vOffset;
  25601. this._cachedUScale = this.uScale;
  25602. this._cachedVScale = this.vScale;
  25603. this._cachedCoordinatesMode = this.coordinatesMode;
  25604. switch (this.coordinatesMode) {
  25605. case Texture.PLANAR_MODE:
  25606. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25607. this._cachedTextureMatrix[0] = this.uScale;
  25608. this._cachedTextureMatrix[5] = this.vScale;
  25609. this._cachedTextureMatrix[12] = this.uOffset;
  25610. this._cachedTextureMatrix[13] = this.vOffset;
  25611. break;
  25612. case Texture.PROJECTION_MODE:
  25613. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25614. this._projectionModeMatrix.m[0] = 0.5;
  25615. this._projectionModeMatrix.m[5] = -0.5;
  25616. this._projectionModeMatrix.m[10] = 0.0;
  25617. this._projectionModeMatrix.m[12] = 0.5;
  25618. this._projectionModeMatrix.m[13] = 0.5;
  25619. this._projectionModeMatrix.m[14] = 1.0;
  25620. this._projectionModeMatrix.m[15] = 1.0;
  25621. var projectionMatrix = scene.getProjectionMatrix();
  25622. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25623. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25624. break;
  25625. default:
  25626. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25627. break;
  25628. }
  25629. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25630. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25631. });
  25632. return this._cachedTextureMatrix;
  25633. };
  25634. Texture.prototype.clone = function () {
  25635. var _this = this;
  25636. return BABYLON.SerializationHelper.Clone(function () {
  25637. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25638. }, this);
  25639. };
  25640. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25641. get: function () {
  25642. if (!this._onLoadObservable) {
  25643. this._onLoadObservable = new BABYLON.Observable();
  25644. }
  25645. return this._onLoadObservable;
  25646. },
  25647. enumerable: true,
  25648. configurable: true
  25649. });
  25650. Texture.prototype.serialize = function () {
  25651. var serializationObject = _super.prototype.serialize.call(this);
  25652. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25653. serializationObject.base64String = this._buffer;
  25654. serializationObject.name = serializationObject.name.replace("data:", "");
  25655. }
  25656. return serializationObject;
  25657. };
  25658. Texture.prototype.getClassName = function () {
  25659. return "Texture";
  25660. };
  25661. Texture.prototype.dispose = function () {
  25662. _super.prototype.dispose.call(this);
  25663. if (this.onLoadObservable) {
  25664. this.onLoadObservable.clear();
  25665. this._onLoadObservable = null;
  25666. }
  25667. this._delayedOnLoad = null;
  25668. this._delayedOnError = null;
  25669. };
  25670. // Statics
  25671. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25672. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25673. if (onLoad === void 0) { onLoad = null; }
  25674. if (onError === void 0) { onError = null; }
  25675. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25676. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25677. };
  25678. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25679. if (parsedTexture.customType) {
  25680. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25681. // Update Sampling Mode
  25682. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25683. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25684. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25685. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25686. }
  25687. }
  25688. return parsedCustomTexture;
  25689. }
  25690. if (parsedTexture.isCube) {
  25691. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25692. }
  25693. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25694. return null;
  25695. }
  25696. var texture = BABYLON.SerializationHelper.Parse(function () {
  25697. var generateMipMaps = true;
  25698. if (parsedTexture.noMipmap) {
  25699. generateMipMaps = false;
  25700. }
  25701. if (parsedTexture.mirrorPlane) {
  25702. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25703. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25704. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25705. return mirrorTexture;
  25706. }
  25707. else if (parsedTexture.isRenderTarget) {
  25708. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25709. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25710. return renderTargetTexture;
  25711. }
  25712. else {
  25713. var texture;
  25714. if (parsedTexture.base64String) {
  25715. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25716. }
  25717. else {
  25718. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25719. }
  25720. return texture;
  25721. }
  25722. }, parsedTexture, scene);
  25723. // Update Sampling Mode
  25724. if (parsedTexture.samplingMode) {
  25725. var sampling = parsedTexture.samplingMode;
  25726. if (texture._samplingMode !== sampling) {
  25727. texture.updateSamplingMode(sampling);
  25728. }
  25729. }
  25730. // Animations
  25731. if (parsedTexture.animations) {
  25732. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25733. var parsedAnimation = parsedTexture.animations[animationIndex];
  25734. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25735. }
  25736. }
  25737. return texture;
  25738. };
  25739. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25740. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25741. if (noMipmap === void 0) { noMipmap = false; }
  25742. if (invertY === void 0) { invertY = true; }
  25743. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25744. if (onLoad === void 0) { onLoad = null; }
  25745. if (onError === void 0) { onError = null; }
  25746. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25747. if (name.substr(0, 5) !== "data:") {
  25748. name = "data:" + name;
  25749. }
  25750. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25751. };
  25752. // Constants
  25753. Texture.NEAREST_SAMPLINGMODE = 1;
  25754. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25755. Texture.BILINEAR_SAMPLINGMODE = 2;
  25756. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25757. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25758. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25759. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25760. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25761. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25762. Texture.NEAREST_LINEAR = 7;
  25763. Texture.NEAREST_NEAREST = 8;
  25764. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25765. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25766. Texture.LINEAR_LINEAR = 11;
  25767. Texture.LINEAR_NEAREST = 12;
  25768. Texture.EXPLICIT_MODE = 0;
  25769. Texture.SPHERICAL_MODE = 1;
  25770. Texture.PLANAR_MODE = 2;
  25771. Texture.CUBIC_MODE = 3;
  25772. Texture.PROJECTION_MODE = 4;
  25773. Texture.SKYBOX_MODE = 5;
  25774. Texture.INVCUBIC_MODE = 6;
  25775. Texture.EQUIRECTANGULAR_MODE = 7;
  25776. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25777. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25778. Texture.CLAMP_ADDRESSMODE = 0;
  25779. Texture.WRAP_ADDRESSMODE = 1;
  25780. Texture.MIRROR_ADDRESSMODE = 2;
  25781. __decorate([
  25782. BABYLON.serialize()
  25783. ], Texture.prototype, "url", void 0);
  25784. __decorate([
  25785. BABYLON.serialize()
  25786. ], Texture.prototype, "uOffset", void 0);
  25787. __decorate([
  25788. BABYLON.serialize()
  25789. ], Texture.prototype, "vOffset", void 0);
  25790. __decorate([
  25791. BABYLON.serialize()
  25792. ], Texture.prototype, "uScale", void 0);
  25793. __decorate([
  25794. BABYLON.serialize()
  25795. ], Texture.prototype, "vScale", void 0);
  25796. __decorate([
  25797. BABYLON.serialize()
  25798. ], Texture.prototype, "uAng", void 0);
  25799. __decorate([
  25800. BABYLON.serialize()
  25801. ], Texture.prototype, "vAng", void 0);
  25802. __decorate([
  25803. BABYLON.serialize()
  25804. ], Texture.prototype, "wAng", void 0);
  25805. __decorate([
  25806. BABYLON.serialize()
  25807. ], Texture.prototype, "isBlocking", null);
  25808. return Texture;
  25809. }(BABYLON.BaseTexture));
  25810. BABYLON.Texture = Texture;
  25811. })(BABYLON || (BABYLON = {}));
  25812. //# sourceMappingURL=babylon.texture.js.map
  25813. var BABYLON;
  25814. (function (BABYLON) {
  25815. var _InstancesBatch = /** @class */ (function () {
  25816. function _InstancesBatch() {
  25817. this.mustReturn = false;
  25818. this.visibleInstances = new Array();
  25819. this.renderSelf = new Array();
  25820. }
  25821. return _InstancesBatch;
  25822. }());
  25823. BABYLON._InstancesBatch = _InstancesBatch;
  25824. var Mesh = /** @class */ (function (_super) {
  25825. __extends(Mesh, _super);
  25826. /**
  25827. * @constructor
  25828. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25829. * @param {Scene} scene The scene to add this mesh to.
  25830. * @param {Node} parent The parent of this mesh, if it has one
  25831. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25832. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25833. * When false, achieved by calling a clone(), also passing False.
  25834. * This will make creation of children, recursive.
  25835. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25836. */
  25837. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25838. if (scene === void 0) { scene = null; }
  25839. if (parent === void 0) { parent = null; }
  25840. if (source === void 0) { source = null; }
  25841. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25842. var _this = _super.call(this, name, scene) || this;
  25843. // Events
  25844. /**
  25845. * An event triggered before rendering the mesh
  25846. * @type {BABYLON.Observable}
  25847. */
  25848. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25849. /**
  25850. * An event triggered after rendering the mesh
  25851. * @type {BABYLON.Observable}
  25852. */
  25853. _this.onAfterRenderObservable = new BABYLON.Observable();
  25854. /**
  25855. * An event triggered before drawing the mesh
  25856. * @type {BABYLON.Observable}
  25857. */
  25858. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25859. // Members
  25860. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25861. _this.instances = new Array();
  25862. _this._LODLevels = new Array();
  25863. _this._visibleInstances = {};
  25864. _this._renderIdForInstances = new Array();
  25865. _this._batchCache = new _InstancesBatch();
  25866. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25867. // Use by builder only to know what orientation were the mesh build in.
  25868. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25869. _this.overrideMaterialSideOrientation = null;
  25870. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25871. // Will be used to save a source mesh reference, If any
  25872. _this._source = null;
  25873. scene = _this.getScene();
  25874. if (source) {
  25875. // Source mesh
  25876. _this._source = source;
  25877. // Geometry
  25878. if (source._geometry) {
  25879. source._geometry.applyToMesh(_this);
  25880. }
  25881. // Deep copy
  25882. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25883. // Metadata
  25884. if (source.metadata && source.metadata.clone) {
  25885. _this.metadata = source.metadata.clone();
  25886. }
  25887. else {
  25888. _this.metadata = source.metadata;
  25889. }
  25890. // Tags
  25891. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25892. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25893. }
  25894. // Parent
  25895. _this.parent = source.parent;
  25896. // Pivot
  25897. _this.setPivotMatrix(source.getPivotMatrix());
  25898. _this.id = name + "." + source.id;
  25899. // Material
  25900. _this.material = source.material;
  25901. var index;
  25902. if (!doNotCloneChildren) {
  25903. // Children
  25904. var directDescendants = source.getDescendants(true);
  25905. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25906. var child = directDescendants[index_1];
  25907. if (child.clone) {
  25908. child.clone(name + "." + child.name, _this);
  25909. }
  25910. }
  25911. }
  25912. // Physics clone
  25913. var physicsEngine = _this.getScene().getPhysicsEngine();
  25914. if (clonePhysicsImpostor && physicsEngine) {
  25915. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25916. if (impostor) {
  25917. _this.physicsImpostor = impostor.clone(_this);
  25918. }
  25919. }
  25920. // Particles
  25921. for (index = 0; index < scene.particleSystems.length; index++) {
  25922. var system = scene.particleSystems[index];
  25923. if (system.emitter === source) {
  25924. system.clone(system.name, _this);
  25925. }
  25926. }
  25927. _this.computeWorldMatrix(true);
  25928. }
  25929. // Parent
  25930. if (parent !== null) {
  25931. _this.parent = parent;
  25932. }
  25933. return _this;
  25934. }
  25935. Object.defineProperty(Mesh, "FRONTSIDE", {
  25936. /**
  25937. * Mesh side orientation : usually the external or front surface
  25938. */
  25939. get: function () {
  25940. return Mesh._FRONTSIDE;
  25941. },
  25942. enumerable: true,
  25943. configurable: true
  25944. });
  25945. Object.defineProperty(Mesh, "BACKSIDE", {
  25946. /**
  25947. * Mesh side orientation : usually the internal or back surface
  25948. */
  25949. get: function () {
  25950. return Mesh._BACKSIDE;
  25951. },
  25952. enumerable: true,
  25953. configurable: true
  25954. });
  25955. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25956. /**
  25957. * Mesh side orientation : both internal and external or front and back surfaces
  25958. */
  25959. get: function () {
  25960. return Mesh._DOUBLESIDE;
  25961. },
  25962. enumerable: true,
  25963. configurable: true
  25964. });
  25965. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25966. /**
  25967. * Mesh side orientation : by default, `FRONTSIDE`
  25968. */
  25969. get: function () {
  25970. return Mesh._DEFAULTSIDE;
  25971. },
  25972. enumerable: true,
  25973. configurable: true
  25974. });
  25975. Object.defineProperty(Mesh, "NO_CAP", {
  25976. /**
  25977. * Mesh cap setting : no cap
  25978. */
  25979. get: function () {
  25980. return Mesh._NO_CAP;
  25981. },
  25982. enumerable: true,
  25983. configurable: true
  25984. });
  25985. Object.defineProperty(Mesh, "CAP_START", {
  25986. /**
  25987. * Mesh cap setting : one cap at the beginning of the mesh
  25988. */
  25989. get: function () {
  25990. return Mesh._CAP_START;
  25991. },
  25992. enumerable: true,
  25993. configurable: true
  25994. });
  25995. Object.defineProperty(Mesh, "CAP_END", {
  25996. /**
  25997. * Mesh cap setting : one cap at the end of the mesh
  25998. */
  25999. get: function () {
  26000. return Mesh._CAP_END;
  26001. },
  26002. enumerable: true,
  26003. configurable: true
  26004. });
  26005. Object.defineProperty(Mesh, "CAP_ALL", {
  26006. /**
  26007. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26008. */
  26009. get: function () {
  26010. return Mesh._CAP_ALL;
  26011. },
  26012. enumerable: true,
  26013. configurable: true
  26014. });
  26015. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26016. set: function (callback) {
  26017. if (this._onBeforeDrawObserver) {
  26018. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26019. }
  26020. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26021. },
  26022. enumerable: true,
  26023. configurable: true
  26024. });
  26025. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26026. get: function () {
  26027. return this._morphTargetManager;
  26028. },
  26029. set: function (value) {
  26030. if (this._morphTargetManager === value) {
  26031. return;
  26032. }
  26033. this._morphTargetManager = value;
  26034. this._syncGeometryWithMorphTargetManager();
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. Object.defineProperty(Mesh.prototype, "source", {
  26040. get: function () {
  26041. return this._source;
  26042. },
  26043. enumerable: true,
  26044. configurable: true
  26045. });
  26046. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26047. get: function () {
  26048. return this._unIndexed;
  26049. },
  26050. set: function (value) {
  26051. if (this._unIndexed !== value) {
  26052. this._unIndexed = value;
  26053. this._markSubMeshesAsAttributesDirty();
  26054. }
  26055. },
  26056. enumerable: true,
  26057. configurable: true
  26058. });
  26059. // Methods
  26060. /**
  26061. * Returns the string "Mesh".
  26062. */
  26063. Mesh.prototype.getClassName = function () {
  26064. return "Mesh";
  26065. };
  26066. /**
  26067. * Returns a string.
  26068. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26069. */
  26070. Mesh.prototype.toString = function (fullDetails) {
  26071. var ret = _super.prototype.toString.call(this, fullDetails);
  26072. ret += ", n vertices: " + this.getTotalVertices();
  26073. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26074. if (this.animations) {
  26075. for (var i = 0; i < this.animations.length; i++) {
  26076. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26077. }
  26078. }
  26079. if (fullDetails) {
  26080. if (this._geometry) {
  26081. var ib = this.getIndices();
  26082. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26083. if (vb && ib) {
  26084. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26085. }
  26086. }
  26087. else {
  26088. ret += ", flat shading: UNKNOWN";
  26089. }
  26090. }
  26091. return ret;
  26092. };
  26093. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26094. /**
  26095. * True if the mesh has some Levels Of Details (LOD).
  26096. * Returns a boolean.
  26097. */
  26098. get: function () {
  26099. return this._LODLevels.length > 0;
  26100. },
  26101. enumerable: true,
  26102. configurable: true
  26103. });
  26104. /**
  26105. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26106. * @returns an array of {BABYLON.MeshLODLevel}
  26107. */
  26108. Mesh.prototype.getLODLevels = function () {
  26109. return this._LODLevels;
  26110. };
  26111. Mesh.prototype._sortLODLevels = function () {
  26112. this._LODLevels.sort(function (a, b) {
  26113. if (a.distance < b.distance) {
  26114. return 1;
  26115. }
  26116. if (a.distance > b.distance) {
  26117. return -1;
  26118. }
  26119. return 0;
  26120. });
  26121. };
  26122. /**
  26123. * Add a mesh as LOD level triggered at the given distance.
  26124. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26125. * @param {number} distance The distance from the center of the object to show this level
  26126. * @param {Mesh} mesh The mesh to be added as LOD level
  26127. * @return {Mesh} This mesh (for chaining)
  26128. */
  26129. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26130. if (mesh && mesh._masterMesh) {
  26131. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26132. return this;
  26133. }
  26134. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26135. this._LODLevels.push(level);
  26136. if (mesh) {
  26137. mesh._masterMesh = this;
  26138. }
  26139. this._sortLODLevels();
  26140. return this;
  26141. };
  26142. /**
  26143. * Returns the LOD level mesh at the passed distance or null if not found.
  26144. * It is related to the method `addLODLevel(distance, mesh)`.
  26145. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26146. * Returns an object Mesh or `null`.
  26147. */
  26148. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26149. for (var index = 0; index < this._LODLevels.length; index++) {
  26150. var level = this._LODLevels[index];
  26151. if (level.distance === distance) {
  26152. return level.mesh;
  26153. }
  26154. }
  26155. return null;
  26156. };
  26157. /**
  26158. * Remove a mesh from the LOD array
  26159. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26160. * @param {Mesh} mesh The mesh to be removed.
  26161. * @return {Mesh} This mesh (for chaining)
  26162. */
  26163. Mesh.prototype.removeLODLevel = function (mesh) {
  26164. for (var index = 0; index < this._LODLevels.length; index++) {
  26165. if (this._LODLevels[index].mesh === mesh) {
  26166. this._LODLevels.splice(index, 1);
  26167. if (mesh) {
  26168. mesh._masterMesh = null;
  26169. }
  26170. }
  26171. }
  26172. this._sortLODLevels();
  26173. return this;
  26174. };
  26175. /**
  26176. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26177. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26178. */
  26179. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26180. if (!this._LODLevels || this._LODLevels.length === 0) {
  26181. return this;
  26182. }
  26183. var bSphere;
  26184. if (boundingSphere) {
  26185. bSphere = boundingSphere;
  26186. }
  26187. else {
  26188. var boundingInfo = this.getBoundingInfo();
  26189. bSphere = boundingInfo.boundingSphere;
  26190. }
  26191. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26192. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26193. if (this.onLODLevelSelection) {
  26194. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26195. }
  26196. return this;
  26197. }
  26198. for (var index = 0; index < this._LODLevels.length; index++) {
  26199. var level = this._LODLevels[index];
  26200. if (level.distance < distanceToCamera) {
  26201. if (level.mesh) {
  26202. level.mesh._preActivate();
  26203. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26204. }
  26205. if (this.onLODLevelSelection) {
  26206. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26207. }
  26208. return level.mesh;
  26209. }
  26210. }
  26211. if (this.onLODLevelSelection) {
  26212. this.onLODLevelSelection(distanceToCamera, this, this);
  26213. }
  26214. return this;
  26215. };
  26216. Object.defineProperty(Mesh.prototype, "geometry", {
  26217. /**
  26218. * Returns the mesh internal Geometry object.
  26219. */
  26220. get: function () {
  26221. return this._geometry;
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. /**
  26227. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26228. */
  26229. Mesh.prototype.getTotalVertices = function () {
  26230. if (this._geometry === null || this._geometry === undefined) {
  26231. return 0;
  26232. }
  26233. return this._geometry.getTotalVertices();
  26234. };
  26235. /**
  26236. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26237. * 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.
  26238. * You can force the copy with forceCopy === true
  26239. * Returns null if the mesh has no geometry or no vertex buffer.
  26240. * Possible `kind` values :
  26241. * - BABYLON.VertexBuffer.PositionKind
  26242. * - BABYLON.VertexBuffer.UVKind
  26243. * - BABYLON.VertexBuffer.UV2Kind
  26244. * - BABYLON.VertexBuffer.UV3Kind
  26245. * - BABYLON.VertexBuffer.UV4Kind
  26246. * - BABYLON.VertexBuffer.UV5Kind
  26247. * - BABYLON.VertexBuffer.UV6Kind
  26248. * - BABYLON.VertexBuffer.ColorKind
  26249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26253. */
  26254. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26255. if (!this._geometry) {
  26256. return null;
  26257. }
  26258. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26259. };
  26260. /**
  26261. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26262. * Returns `null` if the mesh has no geometry.
  26263. * Possible `kind` values :
  26264. * - BABYLON.VertexBuffer.PositionKind
  26265. * - BABYLON.VertexBuffer.UVKind
  26266. * - BABYLON.VertexBuffer.UV2Kind
  26267. * - BABYLON.VertexBuffer.UV3Kind
  26268. * - BABYLON.VertexBuffer.UV4Kind
  26269. * - BABYLON.VertexBuffer.UV5Kind
  26270. * - BABYLON.VertexBuffer.UV6Kind
  26271. * - BABYLON.VertexBuffer.ColorKind
  26272. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26273. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26274. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26275. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26276. */
  26277. Mesh.prototype.getVertexBuffer = function (kind) {
  26278. if (!this._geometry) {
  26279. return null;
  26280. }
  26281. return this._geometry.getVertexBuffer(kind);
  26282. };
  26283. /**
  26284. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26285. * Possible `kind` values :
  26286. * - BABYLON.VertexBuffer.PositionKind
  26287. * - BABYLON.VertexBuffer.UVKind
  26288. * - BABYLON.VertexBuffer.UV2Kind
  26289. * - BABYLON.VertexBuffer.UV3Kind
  26290. * - BABYLON.VertexBuffer.UV4Kind
  26291. * - BABYLON.VertexBuffer.UV5Kind
  26292. * - BABYLON.VertexBuffer.UV6Kind
  26293. * - BABYLON.VertexBuffer.ColorKind
  26294. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26295. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26296. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26297. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26298. */
  26299. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26300. if (!this._geometry) {
  26301. if (this._delayInfo) {
  26302. return this._delayInfo.indexOf(kind) !== -1;
  26303. }
  26304. return false;
  26305. }
  26306. return this._geometry.isVerticesDataPresent(kind);
  26307. };
  26308. /**
  26309. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26310. * Possible `kind` values :
  26311. * - BABYLON.VertexBuffer.PositionKind
  26312. * - BABYLON.VertexBuffer.UVKind
  26313. * - BABYLON.VertexBuffer.UV2Kind
  26314. * - BABYLON.VertexBuffer.UV3Kind
  26315. * - BABYLON.VertexBuffer.UV4Kind
  26316. * - BABYLON.VertexBuffer.UV5Kind
  26317. * - BABYLON.VertexBuffer.UV6Kind
  26318. * - BABYLON.VertexBuffer.ColorKind
  26319. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26320. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26321. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26322. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26323. */
  26324. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26325. if (!this._geometry) {
  26326. if (this._delayInfo) {
  26327. return this._delayInfo.indexOf(kind) !== -1;
  26328. }
  26329. return false;
  26330. }
  26331. return this._geometry.isVertexBufferUpdatable(kind);
  26332. };
  26333. /**
  26334. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26335. * Possible `kind` values :
  26336. * - BABYLON.VertexBuffer.PositionKind
  26337. * - BABYLON.VertexBuffer.UVKind
  26338. * - BABYLON.VertexBuffer.UV2Kind
  26339. * - BABYLON.VertexBuffer.UV3Kind
  26340. * - BABYLON.VertexBuffer.UV4Kind
  26341. * - BABYLON.VertexBuffer.UV5Kind
  26342. * - BABYLON.VertexBuffer.UV6Kind
  26343. * - BABYLON.VertexBuffer.ColorKind
  26344. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26345. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26346. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26347. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26348. */
  26349. Mesh.prototype.getVerticesDataKinds = function () {
  26350. if (!this._geometry) {
  26351. var result = new Array();
  26352. if (this._delayInfo) {
  26353. this._delayInfo.forEach(function (kind, index, array) {
  26354. result.push(kind);
  26355. });
  26356. }
  26357. return result;
  26358. }
  26359. return this._geometry.getVerticesDataKinds();
  26360. };
  26361. /**
  26362. * Returns a positive integer : the total number of indices in this mesh geometry.
  26363. * Returns zero if the mesh has no geometry.
  26364. */
  26365. Mesh.prototype.getTotalIndices = function () {
  26366. if (!this._geometry) {
  26367. return 0;
  26368. }
  26369. return this._geometry.getTotalIndices();
  26370. };
  26371. /**
  26372. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26373. * 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.
  26374. * Returns an empty array if the mesh has no geometry.
  26375. */
  26376. Mesh.prototype.getIndices = function (copyWhenShared) {
  26377. if (!this._geometry) {
  26378. return [];
  26379. }
  26380. return this._geometry.getIndices(copyWhenShared);
  26381. };
  26382. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26383. get: function () {
  26384. return this._masterMesh !== null && this._masterMesh !== undefined;
  26385. },
  26386. enumerable: true,
  26387. configurable: true
  26388. });
  26389. /**
  26390. * Determine if the current mesh is ready to be rendered
  26391. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26392. * @returns true if all associated assets are ready (material, textures, shaders)
  26393. */
  26394. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26395. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26396. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26397. return false;
  26398. }
  26399. if (!_super.prototype.isReady.call(this)) {
  26400. return false;
  26401. }
  26402. if (!this.subMeshes || this.subMeshes.length === 0) {
  26403. return true;
  26404. }
  26405. var engine = this.getEngine();
  26406. var scene = this.getScene();
  26407. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26408. this.computeWorldMatrix();
  26409. var mat = this.material || scene.defaultMaterial;
  26410. if (mat) {
  26411. if (mat.storeEffectOnSubMeshes) {
  26412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26413. var subMesh = _a[_i];
  26414. var effectiveMaterial = subMesh.getMaterial();
  26415. if (effectiveMaterial) {
  26416. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26417. return false;
  26418. }
  26419. }
  26420. }
  26421. }
  26422. else {
  26423. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26424. return false;
  26425. }
  26426. }
  26427. }
  26428. // Shadows
  26429. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26430. var light = _c[_b];
  26431. var generator = light.getShadowGenerator();
  26432. if (generator) {
  26433. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26434. var subMesh = _e[_d];
  26435. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26436. return false;
  26437. }
  26438. }
  26439. }
  26440. }
  26441. // LOD
  26442. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26443. var lod = _g[_f];
  26444. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26445. return false;
  26446. }
  26447. }
  26448. return true;
  26449. };
  26450. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26451. /**
  26452. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26453. * This property is pertinent only for updatable parametric shapes.
  26454. */
  26455. get: function () {
  26456. return this._areNormalsFrozen;
  26457. },
  26458. enumerable: true,
  26459. configurable: true
  26460. });
  26461. /**
  26462. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26463. * It has no effect at all on other shapes.
  26464. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26465. * Returns the Mesh.
  26466. */
  26467. Mesh.prototype.freezeNormals = function () {
  26468. this._areNormalsFrozen = true;
  26469. return this;
  26470. };
  26471. /**
  26472. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26473. * It has no effect at all on other shapes.
  26474. * It reactivates the mesh normals computation if it was previously frozen.
  26475. * Returns the Mesh.
  26476. */
  26477. Mesh.prototype.unfreezeNormals = function () {
  26478. this._areNormalsFrozen = false;
  26479. return this;
  26480. };
  26481. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26482. /**
  26483. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26484. */
  26485. set: function (count) {
  26486. this._overridenInstanceCount = count;
  26487. },
  26488. enumerable: true,
  26489. configurable: true
  26490. });
  26491. // Methods
  26492. Mesh.prototype._preActivate = function () {
  26493. var sceneRenderId = this.getScene().getRenderId();
  26494. if (this._preActivateId === sceneRenderId) {
  26495. return this;
  26496. }
  26497. this._preActivateId = sceneRenderId;
  26498. this._visibleInstances = null;
  26499. return this;
  26500. };
  26501. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26502. if (this._visibleInstances) {
  26503. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26504. }
  26505. return this;
  26506. };
  26507. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26508. if (!this._visibleInstances) {
  26509. this._visibleInstances = {};
  26510. this._visibleInstances.defaultRenderId = renderId;
  26511. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26512. }
  26513. if (!this._visibleInstances[renderId]) {
  26514. this._visibleInstances[renderId] = new Array();
  26515. }
  26516. this._visibleInstances[renderId].push(instance);
  26517. return this;
  26518. };
  26519. /**
  26520. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26521. * This means the mesh underlying bounding box and sphere are recomputed.
  26522. * Returns the Mesh.
  26523. */
  26524. Mesh.prototype.refreshBoundingInfo = function () {
  26525. return this._refreshBoundingInfo(false);
  26526. };
  26527. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26528. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26529. return this;
  26530. }
  26531. var data = this._getPositionData(applySkeleton);
  26532. if (data) {
  26533. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26534. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26535. }
  26536. if (this.subMeshes) {
  26537. for (var index = 0; index < this.subMeshes.length; index++) {
  26538. this.subMeshes[index].refreshBoundingInfo();
  26539. }
  26540. }
  26541. this._updateBoundingInfo();
  26542. return this;
  26543. };
  26544. Mesh.prototype._getPositionData = function (applySkeleton) {
  26545. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26546. if (data && applySkeleton && this.skeleton) {
  26547. data = BABYLON.Tools.Slice(data);
  26548. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26549. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26550. if (matricesWeightsData && matricesIndicesData) {
  26551. var needExtras = this.numBoneInfluencers > 4;
  26552. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26553. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26554. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26555. var tempVector = BABYLON.Tmp.Vector3[0];
  26556. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26557. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26558. var matWeightIdx = 0;
  26559. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26560. finalMatrix.reset();
  26561. var inf;
  26562. var weight;
  26563. for (inf = 0; inf < 4; inf++) {
  26564. weight = matricesWeightsData[matWeightIdx + inf];
  26565. if (weight <= 0)
  26566. break;
  26567. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26568. finalMatrix.addToSelf(tempMatrix);
  26569. }
  26570. if (needExtras) {
  26571. for (inf = 0; inf < 4; inf++) {
  26572. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26573. if (weight <= 0)
  26574. break;
  26575. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26576. finalMatrix.addToSelf(tempMatrix);
  26577. }
  26578. }
  26579. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26580. tempVector.toArray(data, index);
  26581. }
  26582. }
  26583. }
  26584. return data;
  26585. };
  26586. Mesh.prototype._createGlobalSubMesh = function (force) {
  26587. var totalVertices = this.getTotalVertices();
  26588. if (!totalVertices || !this.getIndices()) {
  26589. return null;
  26590. }
  26591. // Check if we need to recreate the submeshes
  26592. if (this.subMeshes && this.subMeshes.length > 0) {
  26593. var ib = this.getIndices();
  26594. if (!ib) {
  26595. return null;
  26596. }
  26597. var totalIndices = ib.length;
  26598. var needToRecreate = false;
  26599. if (force) {
  26600. needToRecreate = true;
  26601. }
  26602. else {
  26603. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26604. var submesh = _a[_i];
  26605. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26606. needToRecreate = true;
  26607. break;
  26608. }
  26609. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26610. needToRecreate = true;
  26611. break;
  26612. }
  26613. }
  26614. }
  26615. if (!needToRecreate) {
  26616. return this.subMeshes[0];
  26617. }
  26618. }
  26619. this.releaseSubMeshes();
  26620. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26621. };
  26622. Mesh.prototype.subdivide = function (count) {
  26623. if (count < 1) {
  26624. return;
  26625. }
  26626. var totalIndices = this.getTotalIndices();
  26627. var subdivisionSize = (totalIndices / count) | 0;
  26628. var offset = 0;
  26629. // Ensure that subdivisionSize is a multiple of 3
  26630. while (subdivisionSize % 3 !== 0) {
  26631. subdivisionSize++;
  26632. }
  26633. this.releaseSubMeshes();
  26634. for (var index = 0; index < count; index++) {
  26635. if (offset >= totalIndices) {
  26636. break;
  26637. }
  26638. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26639. offset += subdivisionSize;
  26640. }
  26641. this.synchronizeInstances();
  26642. };
  26643. /**
  26644. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26645. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26646. * The `data` are either a numeric array either a Float32Array.
  26647. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26648. * 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).
  26649. * Note that a new underlying VertexBuffer object is created each call.
  26650. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26651. *
  26652. * Possible `kind` values :
  26653. * - BABYLON.VertexBuffer.PositionKind
  26654. * - BABYLON.VertexBuffer.UVKind
  26655. * - BABYLON.VertexBuffer.UV2Kind
  26656. * - BABYLON.VertexBuffer.UV3Kind
  26657. * - BABYLON.VertexBuffer.UV4Kind
  26658. * - BABYLON.VertexBuffer.UV5Kind
  26659. * - BABYLON.VertexBuffer.UV6Kind
  26660. * - BABYLON.VertexBuffer.ColorKind
  26661. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26662. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26663. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26664. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26665. *
  26666. * Returns the Mesh.
  26667. */
  26668. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26669. if (updatable === void 0) { updatable = false; }
  26670. if (!this._geometry) {
  26671. var vertexData = new BABYLON.VertexData();
  26672. vertexData.set(data, kind);
  26673. var scene = this.getScene();
  26674. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26675. }
  26676. else {
  26677. this._geometry.setVerticesData(kind, data, updatable, stride);
  26678. }
  26679. return this;
  26680. };
  26681. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26682. if (updatable === void 0) { updatable = true; }
  26683. var vb = this.getVertexBuffer(kind);
  26684. if (!vb || vb.isUpdatable() === updatable) {
  26685. return;
  26686. }
  26687. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26688. };
  26689. /**
  26690. * Sets the mesh VertexBuffer.
  26691. * Returns the Mesh.
  26692. */
  26693. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26694. if (!this._geometry) {
  26695. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26696. }
  26697. this._geometry.setVerticesBuffer(buffer);
  26698. return this;
  26699. };
  26700. /**
  26701. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26702. * If the mesh has no geometry, it is simply returned as it is.
  26703. * The `data` are either a numeric array either a Float32Array.
  26704. * No new underlying VertexBuffer object is created.
  26705. * 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.
  26706. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26707. *
  26708. * Possible `kind` values :
  26709. * - BABYLON.VertexBuffer.PositionKind
  26710. * - BABYLON.VertexBuffer.UVKind
  26711. * - BABYLON.VertexBuffer.UV2Kind
  26712. * - BABYLON.VertexBuffer.UV3Kind
  26713. * - BABYLON.VertexBuffer.UV4Kind
  26714. * - BABYLON.VertexBuffer.UV5Kind
  26715. * - BABYLON.VertexBuffer.UV6Kind
  26716. * - BABYLON.VertexBuffer.ColorKind
  26717. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26718. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26719. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26720. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26721. *
  26722. * Returns the Mesh.
  26723. */
  26724. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26725. if (!this._geometry) {
  26726. return this;
  26727. }
  26728. if (!makeItUnique) {
  26729. this._geometry.updateVerticesData(kind, data, updateExtends);
  26730. }
  26731. else {
  26732. this.makeGeometryUnique();
  26733. this.updateVerticesData(kind, data, updateExtends, false);
  26734. }
  26735. return this;
  26736. };
  26737. /**
  26738. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26739. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26740. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26741. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26742. * Returns the Mesh.
  26743. */
  26744. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26745. if (computeNormals === void 0) { computeNormals = true; }
  26746. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26747. if (!positions) {
  26748. return this;
  26749. }
  26750. positionFunction(positions);
  26751. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26752. if (computeNormals) {
  26753. var indices = this.getIndices();
  26754. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26755. if (!normals) {
  26756. return this;
  26757. }
  26758. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26759. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26760. }
  26761. return this;
  26762. };
  26763. /**
  26764. * Creates a un-shared specific occurence of the geometry for the mesh.
  26765. * Returns the Mesh.
  26766. */
  26767. Mesh.prototype.makeGeometryUnique = function () {
  26768. if (!this._geometry) {
  26769. return this;
  26770. }
  26771. var oldGeometry = this._geometry;
  26772. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26773. oldGeometry.releaseForMesh(this, true);
  26774. geometry.applyToMesh(this);
  26775. return this;
  26776. };
  26777. /**
  26778. * Sets the mesh indices.
  26779. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26780. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26781. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26782. * This method creates a new index buffer each call.
  26783. * Returns the Mesh.
  26784. */
  26785. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26786. if (totalVertices === void 0) { totalVertices = null; }
  26787. if (updatable === void 0) { updatable = false; }
  26788. if (!this._geometry) {
  26789. var vertexData = new BABYLON.VertexData();
  26790. vertexData.indices = indices;
  26791. var scene = this.getScene();
  26792. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26793. }
  26794. else {
  26795. this._geometry.setIndices(indices, totalVertices, updatable);
  26796. }
  26797. return this;
  26798. };
  26799. /**
  26800. * Update the current index buffer
  26801. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26802. * Returns the Mesh.
  26803. */
  26804. Mesh.prototype.updateIndices = function (indices, offset) {
  26805. if (!this._geometry) {
  26806. return this;
  26807. }
  26808. this._geometry.updateIndices(indices, offset);
  26809. return this;
  26810. };
  26811. /**
  26812. * Invert the geometry to move from a right handed system to a left handed one.
  26813. * Returns the Mesh.
  26814. */
  26815. Mesh.prototype.toLeftHanded = function () {
  26816. if (!this._geometry) {
  26817. return this;
  26818. }
  26819. this._geometry.toLeftHanded();
  26820. return this;
  26821. };
  26822. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26823. if (!this._geometry) {
  26824. return this;
  26825. }
  26826. var engine = this.getScene().getEngine();
  26827. // Wireframe
  26828. var indexToBind;
  26829. if (this._unIndexed) {
  26830. indexToBind = null;
  26831. }
  26832. else {
  26833. switch (fillMode) {
  26834. case BABYLON.Material.PointFillMode:
  26835. indexToBind = null;
  26836. break;
  26837. case BABYLON.Material.WireFrameFillMode:
  26838. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26839. break;
  26840. default:
  26841. case BABYLON.Material.TriangleFillMode:
  26842. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26843. break;
  26844. }
  26845. }
  26846. // VBOs
  26847. this._geometry._bind(effect, indexToBind);
  26848. return this;
  26849. };
  26850. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26851. if (alternate === void 0) { alternate = false; }
  26852. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26853. return this;
  26854. }
  26855. this.onBeforeDrawObservable.notifyObservers(this);
  26856. var scene = this.getScene();
  26857. var engine = scene.getEngine();
  26858. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26859. // or triangles as points
  26860. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26861. }
  26862. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26863. // Triangles as wireframe
  26864. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26865. }
  26866. else {
  26867. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26868. }
  26869. if (scene._isAlternateRenderingEnabled && !alternate) {
  26870. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26871. if (!effect || !scene.activeCamera) {
  26872. return this;
  26873. }
  26874. scene._switchToAlternateCameraConfiguration(true);
  26875. this._effectiveMaterial.bindView(effect);
  26876. this._effectiveMaterial.bindViewProjection(effect);
  26877. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26878. this._draw(subMesh, fillMode, instancesCount, true);
  26879. engine.setViewport(scene.activeCamera.viewport);
  26880. scene._switchToAlternateCameraConfiguration(false);
  26881. this._effectiveMaterial.bindView(effect);
  26882. this._effectiveMaterial.bindViewProjection(effect);
  26883. }
  26884. return this;
  26885. };
  26886. /**
  26887. * Registers for this mesh a javascript function called just before the rendering process.
  26888. * This function is passed the current mesh.
  26889. * Return the Mesh.
  26890. */
  26891. Mesh.prototype.registerBeforeRender = function (func) {
  26892. this.onBeforeRenderObservable.add(func);
  26893. return this;
  26894. };
  26895. /**
  26896. * Disposes a previously registered javascript function called before the rendering.
  26897. * This function is passed the current mesh.
  26898. * Returns the Mesh.
  26899. */
  26900. Mesh.prototype.unregisterBeforeRender = function (func) {
  26901. this.onBeforeRenderObservable.removeCallback(func);
  26902. return this;
  26903. };
  26904. /**
  26905. * Registers for this mesh a javascript function called just after the rendering is complete.
  26906. * This function is passed the current mesh.
  26907. * Returns the Mesh.
  26908. */
  26909. Mesh.prototype.registerAfterRender = function (func) {
  26910. this.onAfterRenderObservable.add(func);
  26911. return this;
  26912. };
  26913. /**
  26914. * Disposes a previously registered javascript function called after the rendering.
  26915. * This function is passed the current mesh.
  26916. * Return the Mesh.
  26917. */
  26918. Mesh.prototype.unregisterAfterRender = function (func) {
  26919. this.onAfterRenderObservable.removeCallback(func);
  26920. return this;
  26921. };
  26922. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26923. var scene = this.getScene();
  26924. this._batchCache.mustReturn = false;
  26925. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26926. this._batchCache.visibleInstances[subMeshId] = null;
  26927. if (this._visibleInstances) {
  26928. var currentRenderId = scene.getRenderId();
  26929. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26930. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26931. var selfRenderId = this._renderId;
  26932. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26933. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26934. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26935. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26936. }
  26937. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26938. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26939. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26940. this._batchCache.mustReturn = true;
  26941. return this._batchCache;
  26942. }
  26943. if (currentRenderId !== selfRenderId) {
  26944. this._batchCache.renderSelf[subMeshId] = false;
  26945. }
  26946. }
  26947. this._renderIdForInstances[subMeshId] = currentRenderId;
  26948. }
  26949. return this._batchCache;
  26950. };
  26951. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26952. var visibleInstances = batch.visibleInstances[subMesh._id];
  26953. if (!visibleInstances) {
  26954. return this;
  26955. }
  26956. var matricesCount = visibleInstances.length + 1;
  26957. var bufferSize = matricesCount * 16 * 4;
  26958. var currentInstancesBufferSize = this._instancesBufferSize;
  26959. var instancesBuffer = this._instancesBuffer;
  26960. while (this._instancesBufferSize < bufferSize) {
  26961. this._instancesBufferSize *= 2;
  26962. }
  26963. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26964. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26965. }
  26966. var offset = 0;
  26967. var instancesCount = 0;
  26968. var world = this.getWorldMatrix();
  26969. if (batch.renderSelf[subMesh._id]) {
  26970. world.copyToArray(this._instancesData, offset);
  26971. offset += 16;
  26972. instancesCount++;
  26973. }
  26974. if (visibleInstances) {
  26975. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26976. var instance = visibleInstances[instanceIndex];
  26977. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26978. offset += 16;
  26979. instancesCount++;
  26980. }
  26981. }
  26982. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26983. if (instancesBuffer) {
  26984. instancesBuffer.dispose();
  26985. }
  26986. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26987. this._instancesBuffer = instancesBuffer;
  26988. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26989. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26990. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26991. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26992. }
  26993. else {
  26994. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26995. }
  26996. this._bind(subMesh, effect, fillMode);
  26997. this._draw(subMesh, fillMode, instancesCount);
  26998. engine.unbindInstanceAttributes();
  26999. return this;
  27000. };
  27001. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27002. var scene = this.getScene();
  27003. var engine = scene.getEngine();
  27004. if (hardwareInstancedRendering) {
  27005. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27006. }
  27007. else {
  27008. if (batch.renderSelf[subMesh._id]) {
  27009. // Draw
  27010. if (onBeforeDraw) {
  27011. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27012. }
  27013. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27014. }
  27015. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27016. if (visibleInstancesForSubMesh) {
  27017. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27018. var instance = visibleInstancesForSubMesh[instanceIndex];
  27019. // World
  27020. var world = instance.getWorldMatrix();
  27021. if (onBeforeDraw) {
  27022. onBeforeDraw(true, world, effectiveMaterial);
  27023. }
  27024. // Draw
  27025. this._draw(subMesh, fillMode);
  27026. }
  27027. }
  27028. }
  27029. return this;
  27030. };
  27031. /**
  27032. * Triggers the draw call for the mesh.
  27033. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27034. * Returns the Mesh.
  27035. */
  27036. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27037. this.checkOcclusionQuery();
  27038. if (this._isOccluded) {
  27039. return this;
  27040. }
  27041. var scene = this.getScene();
  27042. // Managing instances
  27043. var batch = this._getInstancesRenderList(subMesh._id);
  27044. if (batch.mustReturn) {
  27045. return this;
  27046. }
  27047. // Checking geometry state
  27048. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27049. return this;
  27050. }
  27051. this.onBeforeRenderObservable.notifyObservers(this);
  27052. var engine = scene.getEngine();
  27053. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27054. // Material
  27055. var material = subMesh.getMaterial();
  27056. if (!material) {
  27057. return this;
  27058. }
  27059. this._effectiveMaterial = material;
  27060. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27061. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27062. return this;
  27063. }
  27064. }
  27065. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27066. return this;
  27067. }
  27068. // Alpha mode
  27069. if (enableAlphaMode) {
  27070. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27071. }
  27072. // Outline - step 1
  27073. var savedDepthWrite = engine.getDepthWrite();
  27074. if (this.renderOutline) {
  27075. engine.setDepthWrite(false);
  27076. scene.getOutlineRenderer().render(subMesh, batch);
  27077. engine.setDepthWrite(savedDepthWrite);
  27078. }
  27079. var effect;
  27080. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27081. effect = subMesh.effect;
  27082. }
  27083. else {
  27084. effect = this._effectiveMaterial.getEffect();
  27085. }
  27086. if (!effect) {
  27087. return this;
  27088. }
  27089. var sideOrientation = this.overrideMaterialSideOrientation;
  27090. if (sideOrientation == null) {
  27091. sideOrientation = this._effectiveMaterial.sideOrientation;
  27092. if (this._getWorldMatrixDeterminant() < 0) {
  27093. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27094. }
  27095. }
  27096. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27097. if (this._effectiveMaterial.forceDepthWrite) {
  27098. engine.setDepthWrite(true);
  27099. }
  27100. // Bind
  27101. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27102. if (!hardwareInstancedRendering) {
  27103. this._bind(subMesh, effect, fillMode);
  27104. }
  27105. var world = this.getWorldMatrix();
  27106. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27107. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27108. }
  27109. else {
  27110. this._effectiveMaterial.bind(world, this);
  27111. }
  27112. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27113. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27114. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27115. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27116. }
  27117. // Draw
  27118. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27119. // Unbind
  27120. this._effectiveMaterial.unbind();
  27121. // Outline - step 2
  27122. if (this.renderOutline && savedDepthWrite) {
  27123. engine.setDepthWrite(true);
  27124. engine.setColorWrite(false);
  27125. scene.getOutlineRenderer().render(subMesh, batch);
  27126. engine.setColorWrite(true);
  27127. }
  27128. // Overlay
  27129. if (this.renderOverlay) {
  27130. var currentMode = engine.getAlphaMode();
  27131. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27132. scene.getOutlineRenderer().render(subMesh, batch, true);
  27133. engine.setAlphaMode(currentMode);
  27134. }
  27135. this.onAfterRenderObservable.notifyObservers(this);
  27136. return this;
  27137. };
  27138. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27139. if (isInstance && effectiveMaterial) {
  27140. effectiveMaterial.bindOnlyWorldMatrix(world);
  27141. }
  27142. };
  27143. /**
  27144. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27145. */
  27146. Mesh.prototype.getEmittedParticleSystems = function () {
  27147. var results = new Array();
  27148. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27149. var particleSystem = this.getScene().particleSystems[index];
  27150. if (particleSystem.emitter === this) {
  27151. results.push(particleSystem);
  27152. }
  27153. }
  27154. return results;
  27155. };
  27156. /**
  27157. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27158. */
  27159. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27160. var results = new Array();
  27161. var descendants = this.getDescendants();
  27162. descendants.push(this);
  27163. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27164. var particleSystem = this.getScene().particleSystems[index];
  27165. var emitter = particleSystem.emitter;
  27166. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27167. results.push(particleSystem);
  27168. }
  27169. }
  27170. return results;
  27171. };
  27172. Mesh.prototype._checkDelayState = function () {
  27173. var scene = this.getScene();
  27174. if (this._geometry) {
  27175. this._geometry.load(scene);
  27176. }
  27177. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27179. this._queueLoad(scene);
  27180. }
  27181. return this;
  27182. };
  27183. Mesh.prototype._queueLoad = function (scene) {
  27184. var _this = this;
  27185. scene._addPendingData(this);
  27186. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27187. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27188. if (data instanceof ArrayBuffer) {
  27189. _this._delayLoadingFunction(data, _this);
  27190. }
  27191. else {
  27192. _this._delayLoadingFunction(JSON.parse(data), _this);
  27193. }
  27194. _this.instances.forEach(function (instance) {
  27195. instance._syncSubMeshes();
  27196. });
  27197. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27198. scene._removePendingData(_this);
  27199. }, function () { }, scene.database, getBinaryData);
  27200. return this;
  27201. };
  27202. /**
  27203. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27204. */
  27205. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27207. return false;
  27208. }
  27209. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27210. return false;
  27211. }
  27212. this._checkDelayState();
  27213. return true;
  27214. };
  27215. /**
  27216. * Sets the mesh material by the material or multiMaterial `id` property.
  27217. * The material `id` is a string identifying the material or the multiMaterial.
  27218. * This method returns the Mesh.
  27219. */
  27220. Mesh.prototype.setMaterialByID = function (id) {
  27221. var materials = this.getScene().materials;
  27222. var index;
  27223. for (index = materials.length - 1; index > -1; index--) {
  27224. if (materials[index].id === id) {
  27225. this.material = materials[index];
  27226. return this;
  27227. }
  27228. }
  27229. // Multi
  27230. var multiMaterials = this.getScene().multiMaterials;
  27231. for (index = multiMaterials.length - 1; index > -1; index--) {
  27232. if (multiMaterials[index].id === id) {
  27233. this.material = multiMaterials[index];
  27234. return this;
  27235. }
  27236. }
  27237. return this;
  27238. };
  27239. /**
  27240. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27241. */
  27242. Mesh.prototype.getAnimatables = function () {
  27243. var results = new Array();
  27244. if (this.material) {
  27245. results.push(this.material);
  27246. }
  27247. if (this.skeleton) {
  27248. results.push(this.skeleton);
  27249. }
  27250. return results;
  27251. };
  27252. /**
  27253. * Modifies the mesh geometry according to the passed transformation matrix.
  27254. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27255. * The mesh normals are modified accordingly the same transformation.
  27256. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27257. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27258. * Returns the Mesh.
  27259. */
  27260. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27261. // Position
  27262. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27263. return this;
  27264. }
  27265. var submeshes = this.subMeshes.splice(0);
  27266. this._resetPointsArrayCache();
  27267. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27268. var temp = new Array();
  27269. var index;
  27270. for (index = 0; index < data.length; index += 3) {
  27271. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27272. }
  27273. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27274. // Normals
  27275. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27276. return this;
  27277. }
  27278. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27279. temp = [];
  27280. for (index = 0; index < data.length; index += 3) {
  27281. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27282. }
  27283. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27284. // flip faces?
  27285. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27286. this.flipFaces();
  27287. }
  27288. // Restore submeshes
  27289. this.releaseSubMeshes();
  27290. this.subMeshes = submeshes;
  27291. return this;
  27292. };
  27293. /**
  27294. * Modifies the mesh geometry according to its own current World Matrix.
  27295. * The mesh World Matrix is then reset.
  27296. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27297. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27298. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27299. * Returns the Mesh.
  27300. */
  27301. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27302. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27303. this.scaling.copyFromFloats(1, 1, 1);
  27304. this.position.copyFromFloats(0, 0, 0);
  27305. this.rotation.copyFromFloats(0, 0, 0);
  27306. //only if quaternion is already set
  27307. if (this.rotationQuaternion) {
  27308. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27309. }
  27310. this._worldMatrix = BABYLON.Matrix.Identity();
  27311. return this;
  27312. };
  27313. Object.defineProperty(Mesh.prototype, "_positions", {
  27314. // Cache
  27315. get: function () {
  27316. if (this._geometry) {
  27317. return this._geometry._positions;
  27318. }
  27319. return null;
  27320. },
  27321. enumerable: true,
  27322. configurable: true
  27323. });
  27324. Mesh.prototype._resetPointsArrayCache = function () {
  27325. if (this._geometry) {
  27326. this._geometry._resetPointsArrayCache();
  27327. }
  27328. return this;
  27329. };
  27330. Mesh.prototype._generatePointsArray = function () {
  27331. if (this._geometry) {
  27332. return this._geometry._generatePointsArray();
  27333. }
  27334. return false;
  27335. };
  27336. /**
  27337. * Returns a new Mesh object generated from the current mesh properties.
  27338. * This method must not get confused with createInstance().
  27339. * The parameter `name` is a string, the name given to the new mesh.
  27340. * The optional parameter `newParent` can be any Node object (default `null`).
  27341. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27342. * 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.
  27343. */
  27344. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27345. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27346. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27347. };
  27348. /**
  27349. * Disposes the Mesh.
  27350. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27351. * Returns nothing.
  27352. */
  27353. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27354. var _this = this;
  27355. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27356. this.morphTargetManager = null;
  27357. if (this._geometry) {
  27358. this._geometry.releaseForMesh(this, true);
  27359. }
  27360. // Sources
  27361. var meshes = this.getScene().meshes;
  27362. meshes.forEach(function (abstractMesh) {
  27363. var mesh = abstractMesh;
  27364. if (mesh._source && mesh._source === _this) {
  27365. mesh._source = null;
  27366. }
  27367. });
  27368. this._source = null;
  27369. // Instances
  27370. if (this._instancesBuffer) {
  27371. this._instancesBuffer.dispose();
  27372. this._instancesBuffer = null;
  27373. }
  27374. while (this.instances.length) {
  27375. this.instances[0].dispose();
  27376. }
  27377. // Highlight layers.
  27378. var highlightLayers = this.getScene().highlightLayers;
  27379. for (var i = 0; i < highlightLayers.length; i++) {
  27380. var highlightLayer = highlightLayers[i];
  27381. if (highlightLayer) {
  27382. highlightLayer.removeMesh(this);
  27383. highlightLayer.removeExcludedMesh(this);
  27384. }
  27385. }
  27386. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27387. };
  27388. /**
  27389. * Modifies the mesh geometry according to a displacement map.
  27390. * 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.
  27391. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27392. * This method returns nothing.
  27393. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27394. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27395. * 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.
  27396. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27397. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27398. *
  27399. * Returns the Mesh.
  27400. */
  27401. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27402. var _this = this;
  27403. var scene = this.getScene();
  27404. var onload = function (img) {
  27405. // Getting height map data
  27406. var canvas = document.createElement("canvas");
  27407. var context = canvas.getContext("2d");
  27408. var heightMapWidth = img.width;
  27409. var heightMapHeight = img.height;
  27410. canvas.width = heightMapWidth;
  27411. canvas.height = heightMapHeight;
  27412. context.drawImage(img, 0, 0);
  27413. // Create VertexData from map data
  27414. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27415. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27416. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27417. //execute success callback, if set
  27418. if (onSuccess) {
  27419. onSuccess(_this);
  27420. }
  27421. };
  27422. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27423. return this;
  27424. };
  27425. /**
  27426. * Modifies the mesh geometry according to a displacementMap buffer.
  27427. * 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.
  27428. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27429. * This method returns nothing.
  27430. * 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.
  27431. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27432. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27433. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27434. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27435. *
  27436. * Returns the Mesh.
  27437. */
  27438. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27439. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27440. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27441. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27442. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27443. return this;
  27444. }
  27445. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27446. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27447. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27448. var position = BABYLON.Vector3.Zero();
  27449. var normal = BABYLON.Vector3.Zero();
  27450. var uv = BABYLON.Vector2.Zero();
  27451. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27452. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27453. for (var index = 0; index < positions.length; index += 3) {
  27454. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27455. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27456. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27457. // Compute height
  27458. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27459. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27460. var pos = (u + v * heightMapWidth) * 4;
  27461. var r = buffer[pos] / 255.0;
  27462. var g = buffer[pos + 1] / 255.0;
  27463. var b = buffer[pos + 2] / 255.0;
  27464. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27465. normal.normalize();
  27466. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27467. position = position.add(normal);
  27468. position.toArray(positions, index);
  27469. }
  27470. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27471. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27472. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27473. return this;
  27474. };
  27475. /**
  27476. * Modify the mesh to get a flat shading rendering.
  27477. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27478. * This method returns the Mesh.
  27479. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27480. */
  27481. Mesh.prototype.convertToFlatShadedMesh = function () {
  27482. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27483. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27484. var kinds = this.getVerticesDataKinds();
  27485. var vbs = {};
  27486. var data = {};
  27487. var newdata = {};
  27488. var updatableNormals = false;
  27489. var kindIndex;
  27490. var kind;
  27491. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27492. kind = kinds[kindIndex];
  27493. var vertexBuffer = this.getVertexBuffer(kind);
  27494. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27495. updatableNormals = vertexBuffer.isUpdatable();
  27496. kinds.splice(kindIndex, 1);
  27497. kindIndex--;
  27498. continue;
  27499. }
  27500. vbs[kind] = vertexBuffer;
  27501. data[kind] = vbs[kind].getData();
  27502. newdata[kind] = [];
  27503. }
  27504. // Save previous submeshes
  27505. var previousSubmeshes = this.subMeshes.slice(0);
  27506. var indices = this.getIndices();
  27507. var totalIndices = this.getTotalIndices();
  27508. // Generating unique vertices per face
  27509. var index;
  27510. for (index = 0; index < totalIndices; index++) {
  27511. var vertexIndex = indices[index];
  27512. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27513. kind = kinds[kindIndex];
  27514. var stride = vbs[kind].getStrideSize();
  27515. for (var offset = 0; offset < stride; offset++) {
  27516. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27517. }
  27518. }
  27519. }
  27520. // Updating faces & normal
  27521. var normals = [];
  27522. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27523. for (index = 0; index < totalIndices; index += 3) {
  27524. indices[index] = index;
  27525. indices[index + 1] = index + 1;
  27526. indices[index + 2] = index + 2;
  27527. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27528. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27529. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27530. var p1p2 = p1.subtract(p2);
  27531. var p3p2 = p3.subtract(p2);
  27532. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27533. // Store same normals for every vertex
  27534. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27535. normals.push(normal.x);
  27536. normals.push(normal.y);
  27537. normals.push(normal.z);
  27538. }
  27539. }
  27540. this.setIndices(indices);
  27541. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27542. // Updating vertex buffers
  27543. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27544. kind = kinds[kindIndex];
  27545. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27546. }
  27547. // Updating submeshes
  27548. this.releaseSubMeshes();
  27549. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27550. var previousOne = previousSubmeshes[submeshIndex];
  27551. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27552. }
  27553. this.synchronizeInstances();
  27554. return this;
  27555. };
  27556. /**
  27557. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27558. * In other words, more vertices, no more indices and a single bigger VBO.
  27559. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27560. * Returns the Mesh.
  27561. */
  27562. Mesh.prototype.convertToUnIndexedMesh = function () {
  27563. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27564. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27565. var kinds = this.getVerticesDataKinds();
  27566. var vbs = {};
  27567. var data = {};
  27568. var newdata = {};
  27569. var kindIndex;
  27570. var kind;
  27571. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27572. kind = kinds[kindIndex];
  27573. var vertexBuffer = this.getVertexBuffer(kind);
  27574. vbs[kind] = vertexBuffer;
  27575. data[kind] = vbs[kind].getData();
  27576. newdata[kind] = [];
  27577. }
  27578. // Save previous submeshes
  27579. var previousSubmeshes = this.subMeshes.slice(0);
  27580. var indices = this.getIndices();
  27581. var totalIndices = this.getTotalIndices();
  27582. // Generating unique vertices per face
  27583. var index;
  27584. for (index = 0; index < totalIndices; index++) {
  27585. var vertexIndex = indices[index];
  27586. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27587. kind = kinds[kindIndex];
  27588. var stride = vbs[kind].getStrideSize();
  27589. for (var offset = 0; offset < stride; offset++) {
  27590. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27591. }
  27592. }
  27593. }
  27594. // Updating indices
  27595. for (index = 0; index < totalIndices; index += 3) {
  27596. indices[index] = index;
  27597. indices[index + 1] = index + 1;
  27598. indices[index + 2] = index + 2;
  27599. }
  27600. this.setIndices(indices);
  27601. // Updating vertex buffers
  27602. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27603. kind = kinds[kindIndex];
  27604. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27605. }
  27606. // Updating submeshes
  27607. this.releaseSubMeshes();
  27608. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27609. var previousOne = previousSubmeshes[submeshIndex];
  27610. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27611. }
  27612. this._unIndexed = true;
  27613. this.synchronizeInstances();
  27614. return this;
  27615. };
  27616. /**
  27617. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27618. * This method returns the Mesh.
  27619. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27620. */
  27621. Mesh.prototype.flipFaces = function (flipNormals) {
  27622. if (flipNormals === void 0) { flipNormals = false; }
  27623. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27624. var i;
  27625. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27626. for (i = 0; i < vertex_data.normals.length; i++) {
  27627. vertex_data.normals[i] *= -1;
  27628. }
  27629. }
  27630. if (vertex_data.indices) {
  27631. var temp;
  27632. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27633. // reassign indices
  27634. temp = vertex_data.indices[i + 1];
  27635. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27636. vertex_data.indices[i + 2] = temp;
  27637. }
  27638. }
  27639. vertex_data.applyToMesh(this);
  27640. return this;
  27641. };
  27642. // Instances
  27643. /**
  27644. * Creates a new InstancedMesh object from the mesh model.
  27645. * An instance shares the same properties and the same material than its model.
  27646. * Only these properties of each instance can then be set individually :
  27647. * - position
  27648. * - rotation
  27649. * - rotationQuaternion
  27650. * - setPivotMatrix
  27651. * - scaling
  27652. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27653. * Warning : this method is not supported for Line mesh and LineSystem
  27654. */
  27655. Mesh.prototype.createInstance = function (name) {
  27656. return new BABYLON.InstancedMesh(name, this);
  27657. };
  27658. /**
  27659. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27660. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27661. * This method returns the Mesh.
  27662. */
  27663. Mesh.prototype.synchronizeInstances = function () {
  27664. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27665. var instance = this.instances[instanceIndex];
  27666. instance._syncSubMeshes();
  27667. }
  27668. return this;
  27669. };
  27670. /**
  27671. * Simplify the mesh according to the given array of settings.
  27672. * Function will return immediately and will simplify async. It returns the Mesh.
  27673. * @param settings a collection of simplification settings.
  27674. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27675. * @param type the type of simplification to run.
  27676. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27677. */
  27678. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27679. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27680. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27681. this.getScene().simplificationQueue.addTask({
  27682. settings: settings,
  27683. parallelProcessing: parallelProcessing,
  27684. mesh: this,
  27685. simplificationType: simplificationType,
  27686. successCallback: successCallback
  27687. });
  27688. return this;
  27689. };
  27690. /**
  27691. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27692. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27693. * This should be used together with the simplification to avoid disappearing triangles.
  27694. * Returns the Mesh.
  27695. * @param successCallback an optional success callback to be called after the optimization finished.
  27696. */
  27697. Mesh.prototype.optimizeIndices = function (successCallback) {
  27698. var _this = this;
  27699. var indices = this.getIndices();
  27700. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27701. if (!positions || !indices) {
  27702. return this;
  27703. }
  27704. var vectorPositions = new Array();
  27705. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27706. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27707. }
  27708. var dupes = new Array();
  27709. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27710. var realPos = vectorPositions.length - 1 - iteration;
  27711. var testedPosition = vectorPositions[realPos];
  27712. for (var j = 0; j < realPos; ++j) {
  27713. var againstPosition = vectorPositions[j];
  27714. if (testedPosition.equals(againstPosition)) {
  27715. dupes[realPos] = j;
  27716. break;
  27717. }
  27718. }
  27719. }, function () {
  27720. for (var i = 0; i < indices.length; ++i) {
  27721. indices[i] = dupes[indices[i]] || indices[i];
  27722. }
  27723. //indices are now reordered
  27724. var originalSubMeshes = _this.subMeshes.slice(0);
  27725. _this.setIndices(indices);
  27726. _this.subMeshes = originalSubMeshes;
  27727. if (successCallback) {
  27728. successCallback(_this);
  27729. }
  27730. });
  27731. return this;
  27732. };
  27733. Mesh.prototype.serialize = function (serializationObject) {
  27734. serializationObject.name = this.name;
  27735. serializationObject.id = this.id;
  27736. serializationObject.type = this.getClassName();
  27737. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27738. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27739. }
  27740. serializationObject.position = this.position.asArray();
  27741. if (this.rotationQuaternion) {
  27742. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27743. }
  27744. else if (this.rotation) {
  27745. serializationObject.rotation = this.rotation.asArray();
  27746. }
  27747. serializationObject.scaling = this.scaling.asArray();
  27748. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27749. serializationObject.isEnabled = this.isEnabled(false);
  27750. serializationObject.isVisible = this.isVisible;
  27751. serializationObject.infiniteDistance = this.infiniteDistance;
  27752. serializationObject.pickable = this.isPickable;
  27753. serializationObject.receiveShadows = this.receiveShadows;
  27754. serializationObject.billboardMode = this.billboardMode;
  27755. serializationObject.visibility = this.visibility;
  27756. serializationObject.checkCollisions = this.checkCollisions;
  27757. serializationObject.isBlocker = this.isBlocker;
  27758. // Parent
  27759. if (this.parent) {
  27760. serializationObject.parentId = this.parent.id;
  27761. }
  27762. // Geometry
  27763. serializationObject.isUnIndexed = this.isUnIndexed;
  27764. var geometry = this._geometry;
  27765. if (geometry) {
  27766. var geometryId = geometry.id;
  27767. serializationObject.geometryId = geometryId;
  27768. // SubMeshes
  27769. serializationObject.subMeshes = [];
  27770. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27771. var subMesh = this.subMeshes[subIndex];
  27772. serializationObject.subMeshes.push({
  27773. materialIndex: subMesh.materialIndex,
  27774. verticesStart: subMesh.verticesStart,
  27775. verticesCount: subMesh.verticesCount,
  27776. indexStart: subMesh.indexStart,
  27777. indexCount: subMesh.indexCount
  27778. });
  27779. }
  27780. }
  27781. // Material
  27782. if (this.material) {
  27783. serializationObject.materialId = this.material.id;
  27784. }
  27785. else {
  27786. this.material = null;
  27787. }
  27788. // Morph targets
  27789. if (this.morphTargetManager) {
  27790. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27791. }
  27792. // Skeleton
  27793. if (this.skeleton) {
  27794. serializationObject.skeletonId = this.skeleton.id;
  27795. }
  27796. // Physics
  27797. //TODO implement correct serialization for physics impostors.
  27798. var impostor = this.getPhysicsImpostor();
  27799. if (impostor) {
  27800. serializationObject.physicsMass = impostor.getParam("mass");
  27801. serializationObject.physicsFriction = impostor.getParam("friction");
  27802. serializationObject.physicsRestitution = impostor.getParam("mass");
  27803. serializationObject.physicsImpostor = impostor.type;
  27804. }
  27805. // Metadata
  27806. if (this.metadata) {
  27807. serializationObject.metadata = this.metadata;
  27808. }
  27809. // Instances
  27810. serializationObject.instances = [];
  27811. for (var index = 0; index < this.instances.length; index++) {
  27812. var instance = this.instances[index];
  27813. var serializationInstance = {
  27814. name: instance.name,
  27815. id: instance.id,
  27816. position: instance.position.asArray(),
  27817. scaling: instance.scaling.asArray()
  27818. };
  27819. if (instance.rotationQuaternion) {
  27820. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27821. }
  27822. else if (instance.rotation) {
  27823. serializationInstance.rotation = instance.rotation.asArray();
  27824. }
  27825. serializationObject.instances.push(serializationInstance);
  27826. // Animations
  27827. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27828. serializationInstance.ranges = instance.serializeAnimationRanges();
  27829. }
  27830. //
  27831. // Animations
  27832. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27833. serializationObject.ranges = this.serializeAnimationRanges();
  27834. // Layer mask
  27835. serializationObject.layerMask = this.layerMask;
  27836. // Alpha
  27837. serializationObject.alphaIndex = this.alphaIndex;
  27838. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27839. // Overlay
  27840. serializationObject.overlayAlpha = this.overlayAlpha;
  27841. serializationObject.overlayColor = this.overlayColor.asArray();
  27842. serializationObject.renderOverlay = this.renderOverlay;
  27843. // Fog
  27844. serializationObject.applyFog = this.applyFog;
  27845. // Action Manager
  27846. if (this.actionManager) {
  27847. serializationObject.actions = this.actionManager.serialize(this.name);
  27848. }
  27849. };
  27850. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27851. if (!this.geometry) {
  27852. return;
  27853. }
  27854. this._markSubMeshesAsAttributesDirty();
  27855. var morphTargetManager = this._morphTargetManager;
  27856. if (morphTargetManager && morphTargetManager.vertexCount) {
  27857. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27858. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27859. this.morphTargetManager = null;
  27860. return;
  27861. }
  27862. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27863. var morphTarget = morphTargetManager.getActiveTarget(index);
  27864. var positions = morphTarget.getPositions();
  27865. if (!positions) {
  27866. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27867. return;
  27868. }
  27869. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27870. var normals = morphTarget.getNormals();
  27871. if (normals) {
  27872. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27873. }
  27874. var tangents = morphTarget.getTangents();
  27875. if (tangents) {
  27876. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27877. }
  27878. }
  27879. }
  27880. else {
  27881. var index = 0;
  27882. // Positions
  27883. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27884. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27885. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27886. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27887. }
  27888. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27889. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27890. }
  27891. index++;
  27892. }
  27893. }
  27894. };
  27895. // Statics
  27896. /**
  27897. * Returns a new Mesh object parsed from the source provided.
  27898. * The parameter `parsedMesh` is the source.
  27899. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27900. */
  27901. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27902. var mesh;
  27903. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27904. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27905. }
  27906. else {
  27907. mesh = new Mesh(parsedMesh.name, scene);
  27908. }
  27909. mesh.id = parsedMesh.id;
  27910. if (BABYLON.Tags) {
  27911. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27912. }
  27913. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27914. if (parsedMesh.metadata !== undefined) {
  27915. mesh.metadata = parsedMesh.metadata;
  27916. }
  27917. if (parsedMesh.rotationQuaternion) {
  27918. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27919. }
  27920. else if (parsedMesh.rotation) {
  27921. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27922. }
  27923. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27924. if (parsedMesh.localMatrix) {
  27925. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27926. }
  27927. else if (parsedMesh.pivotMatrix) {
  27928. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27929. }
  27930. mesh.setEnabled(parsedMesh.isEnabled);
  27931. mesh.isVisible = parsedMesh.isVisible;
  27932. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27933. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27934. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27935. if (parsedMesh.applyFog !== undefined) {
  27936. mesh.applyFog = parsedMesh.applyFog;
  27937. }
  27938. if (parsedMesh.pickable !== undefined) {
  27939. mesh.isPickable = parsedMesh.pickable;
  27940. }
  27941. if (parsedMesh.alphaIndex !== undefined) {
  27942. mesh.alphaIndex = parsedMesh.alphaIndex;
  27943. }
  27944. mesh.receiveShadows = parsedMesh.receiveShadows;
  27945. mesh.billboardMode = parsedMesh.billboardMode;
  27946. if (parsedMesh.visibility !== undefined) {
  27947. mesh.visibility = parsedMesh.visibility;
  27948. }
  27949. mesh.checkCollisions = parsedMesh.checkCollisions;
  27950. if (parsedMesh.isBlocker !== undefined) {
  27951. mesh.isBlocker = parsedMesh.isBlocker;
  27952. }
  27953. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27954. // freezeWorldMatrix
  27955. if (parsedMesh.freezeWorldMatrix) {
  27956. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27957. }
  27958. // Parent
  27959. if (parsedMesh.parentId) {
  27960. mesh._waitingParentId = parsedMesh.parentId;
  27961. }
  27962. // Actions
  27963. if (parsedMesh.actions !== undefined) {
  27964. mesh._waitingActions = parsedMesh.actions;
  27965. }
  27966. // Overlay
  27967. if (parsedMesh.overlayAlpha !== undefined) {
  27968. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27969. }
  27970. if (parsedMesh.overlayColor !== undefined) {
  27971. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27972. }
  27973. if (parsedMesh.renderOverlay !== undefined) {
  27974. mesh.renderOverlay = parsedMesh.renderOverlay;
  27975. }
  27976. // Geometry
  27977. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27978. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27979. if (parsedMesh.delayLoadingFile) {
  27980. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27981. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27982. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27983. if (parsedMesh._binaryInfo) {
  27984. mesh._binaryInfo = parsedMesh._binaryInfo;
  27985. }
  27986. mesh._delayInfo = [];
  27987. if (parsedMesh.hasUVs) {
  27988. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27989. }
  27990. if (parsedMesh.hasUVs2) {
  27991. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27992. }
  27993. if (parsedMesh.hasUVs3) {
  27994. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27995. }
  27996. if (parsedMesh.hasUVs4) {
  27997. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27998. }
  27999. if (parsedMesh.hasUVs5) {
  28000. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28001. }
  28002. if (parsedMesh.hasUVs6) {
  28003. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28004. }
  28005. if (parsedMesh.hasColors) {
  28006. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28007. }
  28008. if (parsedMesh.hasMatricesIndices) {
  28009. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28010. }
  28011. if (parsedMesh.hasMatricesWeights) {
  28012. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28013. }
  28014. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28015. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28016. mesh._checkDelayState();
  28017. }
  28018. }
  28019. else {
  28020. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28021. }
  28022. // Material
  28023. if (parsedMesh.materialId) {
  28024. mesh.setMaterialByID(parsedMesh.materialId);
  28025. }
  28026. else {
  28027. mesh.material = null;
  28028. }
  28029. // Morph targets
  28030. if (parsedMesh.morphTargetManagerId > -1) {
  28031. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28032. }
  28033. // Skeleton
  28034. if (parsedMesh.skeletonId > -1) {
  28035. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28036. if (parsedMesh.numBoneInfluencers) {
  28037. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28038. }
  28039. }
  28040. // Animations
  28041. if (parsedMesh.animations) {
  28042. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28043. var parsedAnimation = parsedMesh.animations[animationIndex];
  28044. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28045. }
  28046. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28047. }
  28048. if (parsedMesh.autoAnimate) {
  28049. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28050. }
  28051. // Layer Mask
  28052. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28053. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28054. }
  28055. else {
  28056. mesh.layerMask = 0x0FFFFFFF;
  28057. }
  28058. // Physics
  28059. if (parsedMesh.physicsImpostor) {
  28060. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28061. mass: parsedMesh.physicsMass,
  28062. friction: parsedMesh.physicsFriction,
  28063. restitution: parsedMesh.physicsRestitution
  28064. }, scene);
  28065. }
  28066. // Instances
  28067. if (parsedMesh.instances) {
  28068. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28069. var parsedInstance = parsedMesh.instances[index];
  28070. var instance = mesh.createInstance(parsedInstance.name);
  28071. if (parsedInstance.id) {
  28072. instance.id = parsedInstance.id;
  28073. }
  28074. if (BABYLON.Tags) {
  28075. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28076. }
  28077. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28078. if (parsedInstance.parentId) {
  28079. instance._waitingParentId = parsedInstance.parentId;
  28080. }
  28081. if (parsedInstance.rotationQuaternion) {
  28082. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28083. }
  28084. else if (parsedInstance.rotation) {
  28085. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28086. }
  28087. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28088. instance.checkCollisions = mesh.checkCollisions;
  28089. if (parsedMesh.animations) {
  28090. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28091. parsedAnimation = parsedMesh.animations[animationIndex];
  28092. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28093. }
  28094. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28095. }
  28096. }
  28097. }
  28098. return mesh;
  28099. };
  28100. /**
  28101. * Creates a ribbon mesh.
  28102. * Please consider using the same method from the MeshBuilder class instead.
  28103. * 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.
  28104. *
  28105. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28106. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28107. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28108. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28109. * 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.
  28110. * 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.
  28111. * 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
  28112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28113. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28115. */
  28116. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28117. if (closeArray === void 0) { closeArray = false; }
  28118. if (updatable === void 0) { updatable = false; }
  28119. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28120. pathArray: pathArray,
  28121. closeArray: closeArray,
  28122. closePath: closePath,
  28123. offset: offset,
  28124. updatable: updatable,
  28125. sideOrientation: sideOrientation,
  28126. instance: instance
  28127. }, scene);
  28128. };
  28129. /**
  28130. * Creates a plane polygonal mesh. By default, this is a disc.
  28131. * Please consider using the same method from the MeshBuilder class instead.
  28132. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28133. * 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.
  28134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28135. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28136. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28137. */
  28138. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28139. if (scene === void 0) { scene = null; }
  28140. var options = {
  28141. radius: radius,
  28142. tessellation: tessellation,
  28143. sideOrientation: sideOrientation,
  28144. updatable: updatable
  28145. };
  28146. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28147. };
  28148. /**
  28149. * Creates a box mesh.
  28150. * Please consider using the same method from the MeshBuilder class instead.
  28151. * The parameter `size` sets the size (float) of each box side (default 1).
  28152. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28153. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28155. */
  28156. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28157. if (scene === void 0) { scene = null; }
  28158. var options = {
  28159. size: size,
  28160. sideOrientation: sideOrientation,
  28161. updatable: updatable
  28162. };
  28163. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28164. };
  28165. /**
  28166. * Creates a sphere mesh.
  28167. * Please consider using the same method from the MeshBuilder class instead.
  28168. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28169. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28173. */
  28174. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28175. var options = {
  28176. segments: segments,
  28177. diameterX: diameter,
  28178. diameterY: diameter,
  28179. diameterZ: diameter,
  28180. sideOrientation: sideOrientation,
  28181. updatable: updatable
  28182. };
  28183. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28184. };
  28185. /**
  28186. * Creates a cylinder or a cone mesh.
  28187. * Please consider using the same method from the MeshBuilder class instead.
  28188. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28189. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28190. * 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.
  28191. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28192. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28194. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28196. */
  28197. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28198. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28199. if (scene !== undefined) {
  28200. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28201. updatable = scene;
  28202. }
  28203. scene = subdivisions;
  28204. subdivisions = 1;
  28205. }
  28206. var options = {
  28207. height: height,
  28208. diameterTop: diameterTop,
  28209. diameterBottom: diameterBottom,
  28210. tessellation: tessellation,
  28211. subdivisions: subdivisions,
  28212. sideOrientation: sideOrientation,
  28213. updatable: updatable
  28214. };
  28215. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28216. };
  28217. // Torus (Code from SharpDX.org)
  28218. /**
  28219. * Creates a torus mesh.
  28220. * Please consider using the same method from the MeshBuilder class instead.
  28221. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28222. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28223. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28227. */
  28228. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28229. var options = {
  28230. diameter: diameter,
  28231. thickness: thickness,
  28232. tessellation: tessellation,
  28233. sideOrientation: sideOrientation,
  28234. updatable: updatable
  28235. };
  28236. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28237. };
  28238. /**
  28239. * Creates a torus knot mesh.
  28240. * Please consider using the same method from the MeshBuilder class instead.
  28241. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28242. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28243. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28244. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28245. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28246. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28248. */
  28249. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28250. var options = {
  28251. radius: radius,
  28252. tube: tube,
  28253. radialSegments: radialSegments,
  28254. tubularSegments: tubularSegments,
  28255. p: p,
  28256. q: q,
  28257. sideOrientation: sideOrientation,
  28258. updatable: updatable
  28259. };
  28260. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28261. };
  28262. /**
  28263. * Creates a line mesh.
  28264. * Please consider using the same method from the MeshBuilder class instead.
  28265. * 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.
  28266. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28267. * The parameter `points` is an array successive Vector3.
  28268. * 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
  28269. * When updating an instance, remember that only point positions can change, not the number of points.
  28270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28271. */
  28272. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28273. if (scene === void 0) { scene = null; }
  28274. if (updatable === void 0) { updatable = false; }
  28275. if (instance === void 0) { instance = null; }
  28276. var options = {
  28277. points: points,
  28278. updatable: updatable,
  28279. instance: instance
  28280. };
  28281. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28282. };
  28283. /**
  28284. * Creates a dashed line mesh.
  28285. * Please consider using the same method from the MeshBuilder class instead.
  28286. * 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.
  28287. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28288. * The parameter `points` is an array successive Vector3.
  28289. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28290. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28291. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28292. * 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
  28293. * When updating an instance, remember that only point positions can change, not the number of points.
  28294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28295. */
  28296. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28297. if (scene === void 0) { scene = null; }
  28298. var options = {
  28299. points: points,
  28300. dashSize: dashSize,
  28301. gapSize: gapSize,
  28302. dashNb: dashNb,
  28303. updatable: updatable,
  28304. instance: instance
  28305. };
  28306. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28307. };
  28308. /**
  28309. * Creates a polygon mesh.
  28310. * Please consider using the same method from the MeshBuilder class instead.
  28311. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28312. * 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.
  28313. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28315. * Remember you can only change the shape positions, not their number when updating a polygon.
  28316. */
  28317. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28318. var options = {
  28319. shape: shape,
  28320. holes: holes,
  28321. updatable: updatable,
  28322. sideOrientation: sideOrientation
  28323. };
  28324. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28325. };
  28326. /**
  28327. * Creates an extruded polygon mesh, with depth in the Y direction.
  28328. * Please consider using the same method from the MeshBuilder class instead.
  28329. */
  28330. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28331. var options = {
  28332. shape: shape,
  28333. holes: holes,
  28334. depth: depth,
  28335. updatable: updatable,
  28336. sideOrientation: sideOrientation
  28337. };
  28338. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28339. };
  28340. /**
  28341. * Creates an extruded shape mesh.
  28342. * 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.
  28343. * Please consider using the same method from the MeshBuilder class instead.
  28344. *
  28345. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28346. * 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
  28347. * extruded along the Z axis.
  28348. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28349. * 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.
  28350. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28351. * 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
  28352. * 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
  28353. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28355. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28357. */
  28358. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28359. if (scene === void 0) { scene = null; }
  28360. var options = {
  28361. shape: shape,
  28362. path: path,
  28363. scale: scale,
  28364. rotation: rotation,
  28365. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28366. sideOrientation: sideOrientation,
  28367. instance: instance,
  28368. updatable: updatable
  28369. };
  28370. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28371. };
  28372. /**
  28373. * Creates an custom extruded shape mesh.
  28374. * 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.
  28375. * Please consider using the same method from the MeshBuilder class instead.
  28376. *
  28377. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28378. * 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
  28379. * extruded along the Z axis.
  28380. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28381. * 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
  28382. * and the distance of this point from the begining of the path :
  28383. * ```javascript
  28384. * var rotationFunction = function(i, distance) {
  28385. * // do things
  28386. * return rotationValue; }
  28387. * ```
  28388. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28389. * 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
  28390. * and the distance of this point from the begining of the path :
  28391. * ```javascript
  28392. * var scaleFunction = function(i, distance) {
  28393. * // do things
  28394. * return scaleValue;}
  28395. * ```
  28396. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28397. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28398. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28399. * 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
  28400. * 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
  28401. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28402. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28405. */
  28406. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28407. var options = {
  28408. shape: shape,
  28409. path: path,
  28410. scaleFunction: scaleFunction,
  28411. rotationFunction: rotationFunction,
  28412. ribbonCloseArray: ribbonCloseArray,
  28413. ribbonClosePath: ribbonClosePath,
  28414. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28415. sideOrientation: sideOrientation,
  28416. instance: instance,
  28417. updatable: updatable
  28418. };
  28419. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28420. };
  28421. /**
  28422. * Creates lathe mesh.
  28423. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28424. * Please consider using the same method from the MeshBuilder class instead.
  28425. * 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
  28426. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28427. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28428. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28432. */
  28433. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28434. var options = {
  28435. shape: shape,
  28436. radius: radius,
  28437. tessellation: tessellation,
  28438. sideOrientation: sideOrientation,
  28439. updatable: updatable
  28440. };
  28441. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28442. };
  28443. /**
  28444. * Creates a plane mesh.
  28445. * Please consider using the same method from the MeshBuilder class instead.
  28446. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28450. */
  28451. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28452. var options = {
  28453. size: size,
  28454. width: size,
  28455. height: size,
  28456. sideOrientation: sideOrientation,
  28457. updatable: updatable
  28458. };
  28459. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28460. };
  28461. /**
  28462. * Creates a ground mesh.
  28463. * Please consider using the same method from the MeshBuilder class instead.
  28464. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28465. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28467. */
  28468. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28469. var options = {
  28470. width: width,
  28471. height: height,
  28472. subdivisions: subdivisions,
  28473. updatable: updatable
  28474. };
  28475. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28476. };
  28477. /**
  28478. * Creates a tiled ground mesh.
  28479. * Please consider using the same method from the MeshBuilder class instead.
  28480. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28481. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28482. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28483. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28484. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28485. * numbers of subdivisions on the ground width and height of each tile.
  28486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28487. */
  28488. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28489. var options = {
  28490. xmin: xmin,
  28491. zmin: zmin,
  28492. xmax: xmax,
  28493. zmax: zmax,
  28494. subdivisions: subdivisions,
  28495. precision: precision,
  28496. updatable: updatable
  28497. };
  28498. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28499. };
  28500. /**
  28501. * Creates a ground mesh from a height map.
  28502. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28503. * Please consider using the same method from the MeshBuilder class instead.
  28504. * The parameter `url` sets the URL of the height map image resource.
  28505. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28506. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28507. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28508. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28509. * 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).
  28510. * This function is passed the newly built mesh :
  28511. * ```javascript
  28512. * function(mesh) { // do things
  28513. * return; }
  28514. * ```
  28515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28516. */
  28517. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28518. var options = {
  28519. width: width,
  28520. height: height,
  28521. subdivisions: subdivisions,
  28522. minHeight: minHeight,
  28523. maxHeight: maxHeight,
  28524. updatable: updatable,
  28525. onReady: onReady
  28526. };
  28527. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28528. };
  28529. /**
  28530. * Creates a tube mesh.
  28531. * 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.
  28532. * Please consider using the same method from the MeshBuilder class instead.
  28533. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28534. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28535. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28536. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28537. * 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.
  28538. * It must return a radius value (positive float) :
  28539. * ```javascript
  28540. * var radiusFunction = function(i, distance) {
  28541. * // do things
  28542. * return radius; }
  28543. * ```
  28544. * 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
  28545. * 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
  28546. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28547. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28549. */
  28550. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28551. var options = {
  28552. path: path,
  28553. radius: radius,
  28554. tessellation: tessellation,
  28555. radiusFunction: radiusFunction,
  28556. arc: 1,
  28557. cap: cap,
  28558. updatable: updatable,
  28559. sideOrientation: sideOrientation,
  28560. instance: instance
  28561. };
  28562. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28563. };
  28564. /**
  28565. * Creates a polyhedron mesh.
  28566. * Please consider using the same method from the MeshBuilder class instead.
  28567. * 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
  28568. * to choose the wanted type.
  28569. * The parameter `size` (positive float, default 1) sets the polygon size.
  28570. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28571. * 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`.
  28572. * 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
  28573. * 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)`).
  28574. * 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
  28575. * 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.
  28576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28579. */
  28580. Mesh.CreatePolyhedron = function (name, options, scene) {
  28581. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28582. };
  28583. /**
  28584. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28585. * Please consider using the same method from the MeshBuilder class instead.
  28586. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28587. * 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`).
  28588. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28589. * 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.
  28590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28593. */
  28594. Mesh.CreateIcoSphere = function (name, options, scene) {
  28595. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28596. };
  28597. /**
  28598. * Creates a decal mesh.
  28599. * Please consider using the same method from the MeshBuilder class instead.
  28600. * 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.
  28601. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28602. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28603. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28604. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28605. */
  28606. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28607. var options = {
  28608. position: position,
  28609. normal: normal,
  28610. size: size,
  28611. angle: angle
  28612. };
  28613. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28614. };
  28615. // Skeletons
  28616. /**
  28617. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28618. */
  28619. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28620. if (!this._sourcePositions) {
  28621. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28622. if (!source) {
  28623. return this._sourcePositions;
  28624. }
  28625. this._sourcePositions = new Float32Array(source);
  28626. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28627. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28628. }
  28629. }
  28630. return this._sourcePositions;
  28631. };
  28632. /**
  28633. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28634. */
  28635. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28636. if (!this._sourceNormals) {
  28637. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28638. if (!source) {
  28639. return this._sourceNormals;
  28640. }
  28641. this._sourceNormals = new Float32Array(source);
  28642. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28643. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28644. }
  28645. }
  28646. return this._sourceNormals;
  28647. };
  28648. /**
  28649. * Updates the vertex buffer by applying transformation from the bones.
  28650. * Returns the Mesh.
  28651. *
  28652. * @param {skeleton} skeleton to apply
  28653. */
  28654. Mesh.prototype.applySkeleton = function (skeleton) {
  28655. if (!this.geometry) {
  28656. return this;
  28657. }
  28658. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28659. return this;
  28660. }
  28661. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28662. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28663. return this;
  28664. }
  28665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28666. return this;
  28667. }
  28668. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28669. return this;
  28670. }
  28671. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28672. return this;
  28673. }
  28674. if (!this._sourcePositions) {
  28675. var submeshes = this.subMeshes.slice();
  28676. this.setPositionsForCPUSkinning();
  28677. this.subMeshes = submeshes;
  28678. }
  28679. if (!this._sourceNormals) {
  28680. this.setNormalsForCPUSkinning();
  28681. }
  28682. // positionsData checks for not being Float32Array will only pass at most once
  28683. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28684. if (!positionsData) {
  28685. return this;
  28686. }
  28687. if (!(positionsData instanceof Float32Array)) {
  28688. positionsData = new Float32Array(positionsData);
  28689. }
  28690. // normalsData checks for not being Float32Array will only pass at most once
  28691. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28692. if (!normalsData) {
  28693. return this;
  28694. }
  28695. if (!(normalsData instanceof Float32Array)) {
  28696. normalsData = new Float32Array(normalsData);
  28697. }
  28698. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28699. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28700. if (!matricesWeightsData || !matricesIndicesData) {
  28701. return this;
  28702. }
  28703. var needExtras = this.numBoneInfluencers > 4;
  28704. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28705. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28706. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28707. var tempVector3 = BABYLON.Vector3.Zero();
  28708. var finalMatrix = new BABYLON.Matrix();
  28709. var tempMatrix = new BABYLON.Matrix();
  28710. var matWeightIdx = 0;
  28711. var inf;
  28712. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28713. var weight;
  28714. for (inf = 0; inf < 4; inf++) {
  28715. weight = matricesWeightsData[matWeightIdx + inf];
  28716. if (weight > 0) {
  28717. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28718. finalMatrix.addToSelf(tempMatrix);
  28719. }
  28720. else
  28721. break;
  28722. }
  28723. if (needExtras) {
  28724. for (inf = 0; inf < 4; inf++) {
  28725. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28726. if (weight > 0) {
  28727. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28728. finalMatrix.addToSelf(tempMatrix);
  28729. }
  28730. else
  28731. break;
  28732. }
  28733. }
  28734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28735. tempVector3.toArray(positionsData, index);
  28736. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28737. tempVector3.toArray(normalsData, index);
  28738. finalMatrix.reset();
  28739. }
  28740. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28741. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28742. return this;
  28743. };
  28744. // Tools
  28745. /**
  28746. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28747. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28748. */
  28749. Mesh.MinMax = function (meshes) {
  28750. var minVector = null;
  28751. var maxVector = null;
  28752. meshes.forEach(function (mesh, index, array) {
  28753. var boundingInfo = mesh.getBoundingInfo();
  28754. var boundingBox = boundingInfo.boundingBox;
  28755. if (!minVector || !maxVector) {
  28756. minVector = boundingBox.minimumWorld;
  28757. maxVector = boundingBox.maximumWorld;
  28758. }
  28759. else {
  28760. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28761. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28762. }
  28763. });
  28764. if (!minVector || !maxVector) {
  28765. return {
  28766. min: BABYLON.Vector3.Zero(),
  28767. max: BABYLON.Vector3.Zero()
  28768. };
  28769. }
  28770. return {
  28771. min: minVector,
  28772. max: maxVector
  28773. };
  28774. };
  28775. /**
  28776. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28777. */
  28778. Mesh.Center = function (meshesOrMinMaxVector) {
  28779. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28780. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28781. };
  28782. /**
  28783. * Merge the array of meshes into a single mesh for performance reasons.
  28784. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28785. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28786. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28787. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28788. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28789. */
  28790. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28791. if (disposeSource === void 0) { disposeSource = true; }
  28792. var index;
  28793. if (!allow32BitsIndices) {
  28794. var totalVertices = 0;
  28795. // Counting vertices
  28796. for (index = 0; index < meshes.length; index++) {
  28797. if (meshes[index]) {
  28798. totalVertices += meshes[index].getTotalVertices();
  28799. if (totalVertices > 65536) {
  28800. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28801. return null;
  28802. }
  28803. }
  28804. }
  28805. }
  28806. // Merge
  28807. var vertexData = null;
  28808. var otherVertexData;
  28809. var indiceArray = new Array();
  28810. var source = null;
  28811. for (index = 0; index < meshes.length; index++) {
  28812. if (meshes[index]) {
  28813. meshes[index].computeWorldMatrix(true);
  28814. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28815. otherVertexData.transform(meshes[index].getWorldMatrix());
  28816. if (vertexData) {
  28817. vertexData.merge(otherVertexData);
  28818. }
  28819. else {
  28820. vertexData = otherVertexData;
  28821. source = meshes[index];
  28822. }
  28823. if (subdivideWithSubMeshes) {
  28824. indiceArray.push(meshes[index].getTotalIndices());
  28825. }
  28826. }
  28827. }
  28828. source = source;
  28829. if (!meshSubclass) {
  28830. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28831. }
  28832. vertexData.applyToMesh(meshSubclass);
  28833. // Setting properties
  28834. meshSubclass.material = source.material;
  28835. meshSubclass.checkCollisions = source.checkCollisions;
  28836. // Cleaning
  28837. if (disposeSource) {
  28838. for (index = 0; index < meshes.length; index++) {
  28839. if (meshes[index]) {
  28840. meshes[index].dispose();
  28841. }
  28842. }
  28843. }
  28844. // Subdivide
  28845. if (subdivideWithSubMeshes) {
  28846. //-- Suppresions du submesh global
  28847. meshSubclass.releaseSubMeshes();
  28848. index = 0;
  28849. var offset = 0;
  28850. //-- aplique la subdivision en fonction du tableau d'indices
  28851. while (index < indiceArray.length) {
  28852. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28853. offset += indiceArray[index];
  28854. index++;
  28855. }
  28856. }
  28857. return meshSubclass;
  28858. };
  28859. // Consts
  28860. Mesh._FRONTSIDE = 0;
  28861. Mesh._BACKSIDE = 1;
  28862. Mesh._DOUBLESIDE = 2;
  28863. Mesh._DEFAULTSIDE = 0;
  28864. Mesh._NO_CAP = 0;
  28865. Mesh._CAP_START = 1;
  28866. Mesh._CAP_END = 2;
  28867. Mesh._CAP_ALL = 3;
  28868. return Mesh;
  28869. }(BABYLON.AbstractMesh));
  28870. BABYLON.Mesh = Mesh;
  28871. })(BABYLON || (BABYLON = {}));
  28872. //# sourceMappingURL=babylon.mesh.js.map
  28873. var BABYLON;
  28874. (function (BABYLON) {
  28875. var BaseSubMesh = /** @class */ (function () {
  28876. function BaseSubMesh() {
  28877. }
  28878. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28879. get: function () {
  28880. return this._materialEffect;
  28881. },
  28882. enumerable: true,
  28883. configurable: true
  28884. });
  28885. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28886. if (defines === void 0) { defines = null; }
  28887. if (this._materialEffect === effect) {
  28888. if (!effect) {
  28889. this._materialDefines = null;
  28890. }
  28891. return;
  28892. }
  28893. this._materialDefines = defines;
  28894. this._materialEffect = effect;
  28895. };
  28896. return BaseSubMesh;
  28897. }());
  28898. BABYLON.BaseSubMesh = BaseSubMesh;
  28899. var SubMesh = /** @class */ (function (_super) {
  28900. __extends(SubMesh, _super);
  28901. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28902. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28903. var _this = _super.call(this) || this;
  28904. _this.materialIndex = materialIndex;
  28905. _this.verticesStart = verticesStart;
  28906. _this.verticesCount = verticesCount;
  28907. _this.indexStart = indexStart;
  28908. _this.indexCount = indexCount;
  28909. _this._renderId = 0;
  28910. _this._mesh = mesh;
  28911. _this._renderingMesh = renderingMesh || mesh;
  28912. mesh.subMeshes.push(_this);
  28913. _this._trianglePlanes = [];
  28914. _this._id = mesh.subMeshes.length - 1;
  28915. if (createBoundingBox) {
  28916. _this.refreshBoundingInfo();
  28917. mesh.computeWorldMatrix(true);
  28918. }
  28919. return _this;
  28920. }
  28921. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28922. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28923. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28924. };
  28925. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28926. get: function () {
  28927. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28928. },
  28929. enumerable: true,
  28930. configurable: true
  28931. });
  28932. /**
  28933. * Returns the submesh BoudingInfo object.
  28934. */
  28935. SubMesh.prototype.getBoundingInfo = function () {
  28936. if (this.IsGlobal) {
  28937. return this._mesh.getBoundingInfo();
  28938. }
  28939. return this._boundingInfo;
  28940. };
  28941. /**
  28942. * Sets the submesh BoundingInfo.
  28943. * Return the SubMesh.
  28944. */
  28945. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28946. this._boundingInfo = boundingInfo;
  28947. return this;
  28948. };
  28949. /**
  28950. * Returns the mesh of the current submesh.
  28951. */
  28952. SubMesh.prototype.getMesh = function () {
  28953. return this._mesh;
  28954. };
  28955. /**
  28956. * Returns the rendering mesh of the submesh.
  28957. */
  28958. SubMesh.prototype.getRenderingMesh = function () {
  28959. return this._renderingMesh;
  28960. };
  28961. /**
  28962. * Returns the submesh material.
  28963. */
  28964. SubMesh.prototype.getMaterial = function () {
  28965. var rootMaterial = this._renderingMesh.material;
  28966. if (rootMaterial === null || rootMaterial === undefined) {
  28967. return this._mesh.getScene().defaultMaterial;
  28968. }
  28969. else if (rootMaterial.getSubMaterial) {
  28970. var multiMaterial = rootMaterial;
  28971. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28972. if (this._currentMaterial !== effectiveMaterial) {
  28973. this._currentMaterial = effectiveMaterial;
  28974. this._materialDefines = null;
  28975. }
  28976. return effectiveMaterial;
  28977. }
  28978. return rootMaterial;
  28979. };
  28980. // Methods
  28981. /**
  28982. * Sets a new updated BoundingInfo object to the submesh.
  28983. * Returns the SubMesh.
  28984. */
  28985. SubMesh.prototype.refreshBoundingInfo = function () {
  28986. this._lastColliderWorldVertices = null;
  28987. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28988. return this;
  28989. }
  28990. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28991. if (!data) {
  28992. this._boundingInfo = this._mesh.getBoundingInfo();
  28993. return this;
  28994. }
  28995. var indices = this._renderingMesh.getIndices();
  28996. var extend;
  28997. //is this the only submesh?
  28998. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28999. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29000. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29001. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29002. }
  29003. else {
  29004. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29005. }
  29006. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29007. return this;
  29008. };
  29009. SubMesh.prototype._checkCollision = function (collider) {
  29010. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29011. return boundingInfo._checkCollision(collider);
  29012. };
  29013. /**
  29014. * Updates the submesh BoundingInfo.
  29015. * Returns the Submesh.
  29016. */
  29017. SubMesh.prototype.updateBoundingInfo = function (world) {
  29018. var boundingInfo = this.getBoundingInfo();
  29019. if (!boundingInfo) {
  29020. this.refreshBoundingInfo();
  29021. boundingInfo = this.getBoundingInfo();
  29022. }
  29023. boundingInfo.update(world);
  29024. return this;
  29025. };
  29026. /**
  29027. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29028. * Boolean returned.
  29029. */
  29030. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29031. var boundingInfo = this.getBoundingInfo();
  29032. if (!boundingInfo) {
  29033. return false;
  29034. }
  29035. return boundingInfo.isInFrustum(frustumPlanes);
  29036. };
  29037. /**
  29038. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29039. * Boolean returned.
  29040. */
  29041. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29042. var boundingInfo = this.getBoundingInfo();
  29043. if (!boundingInfo) {
  29044. return false;
  29045. }
  29046. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29047. };
  29048. /**
  29049. * Renders the submesh.
  29050. * Returns it.
  29051. */
  29052. SubMesh.prototype.render = function (enableAlphaMode) {
  29053. this._renderingMesh.render(this, enableAlphaMode);
  29054. return this;
  29055. };
  29056. /**
  29057. * Returns a new Index Buffer.
  29058. * Type returned : WebGLBuffer.
  29059. */
  29060. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29061. if (!this._linesIndexBuffer) {
  29062. var linesIndices = [];
  29063. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29064. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29065. }
  29066. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29067. this.linesIndexCount = linesIndices.length;
  29068. }
  29069. return this._linesIndexBuffer;
  29070. };
  29071. /**
  29072. * True is the passed Ray intersects the submesh bounding box.
  29073. * Boolean returned.
  29074. */
  29075. SubMesh.prototype.canIntersects = function (ray) {
  29076. var boundingInfo = this.getBoundingInfo();
  29077. if (!boundingInfo) {
  29078. return false;
  29079. }
  29080. return ray.intersectsBox(boundingInfo.boundingBox);
  29081. };
  29082. /**
  29083. * Returns an object IntersectionInfo.
  29084. */
  29085. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29086. var intersectInfo = null;
  29087. // LineMesh first as it's also a Mesh...
  29088. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29089. var lineMesh = this._mesh;
  29090. // Line test
  29091. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29092. var p0 = positions[indices[index]];
  29093. var p1 = positions[indices[index + 1]];
  29094. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29095. if (length < 0) {
  29096. continue;
  29097. }
  29098. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29099. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29100. if (fastCheck) {
  29101. break;
  29102. }
  29103. }
  29104. }
  29105. }
  29106. else {
  29107. // Triangles test
  29108. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29109. var p0 = positions[indices[index]];
  29110. var p1 = positions[indices[index + 1]];
  29111. var p2 = positions[indices[index + 2]];
  29112. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29113. if (currentIntersectInfo) {
  29114. if (currentIntersectInfo.distance < 0) {
  29115. continue;
  29116. }
  29117. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29118. intersectInfo = currentIntersectInfo;
  29119. intersectInfo.faceId = index / 3;
  29120. if (fastCheck) {
  29121. break;
  29122. }
  29123. }
  29124. }
  29125. }
  29126. }
  29127. return intersectInfo;
  29128. };
  29129. SubMesh.prototype._rebuild = function () {
  29130. if (this._linesIndexBuffer) {
  29131. this._linesIndexBuffer = null;
  29132. }
  29133. };
  29134. // Clone
  29135. /**
  29136. * Creates a new Submesh from the passed Mesh.
  29137. */
  29138. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29139. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29140. if (!this.IsGlobal) {
  29141. var boundingInfo = this.getBoundingInfo();
  29142. if (!boundingInfo) {
  29143. return result;
  29144. }
  29145. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29146. }
  29147. return result;
  29148. };
  29149. // Dispose
  29150. /**
  29151. * Disposes the Submesh.
  29152. * Returns nothing.
  29153. */
  29154. SubMesh.prototype.dispose = function () {
  29155. if (this._linesIndexBuffer) {
  29156. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29157. this._linesIndexBuffer = null;
  29158. }
  29159. // Remove from mesh
  29160. var index = this._mesh.subMeshes.indexOf(this);
  29161. this._mesh.subMeshes.splice(index, 1);
  29162. };
  29163. // Statics
  29164. /**
  29165. * Creates a new Submesh from the passed parameters :
  29166. * - materialIndex (integer) : the index of the main mesh material.
  29167. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29168. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29169. * - mesh (Mesh) : the main mesh to create the submesh from.
  29170. * - renderingMesh (optional Mesh) : rendering mesh.
  29171. */
  29172. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29173. var minVertexIndex = Number.MAX_VALUE;
  29174. var maxVertexIndex = -Number.MAX_VALUE;
  29175. renderingMesh = (renderingMesh || mesh);
  29176. var indices = renderingMesh.getIndices();
  29177. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29178. var vertexIndex = indices[index];
  29179. if (vertexIndex < minVertexIndex)
  29180. minVertexIndex = vertexIndex;
  29181. if (vertexIndex > maxVertexIndex)
  29182. maxVertexIndex = vertexIndex;
  29183. }
  29184. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29185. };
  29186. return SubMesh;
  29187. }(BaseSubMesh));
  29188. BABYLON.SubMesh = SubMesh;
  29189. })(BABYLON || (BABYLON = {}));
  29190. //# sourceMappingURL=babylon.subMesh.js.map
  29191. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29192. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29193. s = arguments[i];
  29194. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29195. t[p] = s[p];
  29196. }
  29197. return t;
  29198. };
  29199. var BABYLON;
  29200. (function (BABYLON) {
  29201. var MaterialDefines = /** @class */ (function () {
  29202. function MaterialDefines() {
  29203. this._isDirty = true;
  29204. this._areLightsDirty = true;
  29205. this._areAttributesDirty = true;
  29206. this._areTexturesDirty = true;
  29207. this._areFresnelDirty = true;
  29208. this._areMiscDirty = true;
  29209. this._areImageProcessingDirty = true;
  29210. this._normals = false;
  29211. this._uvs = false;
  29212. this._needNormals = false;
  29213. this._needUVs = false;
  29214. }
  29215. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29216. get: function () {
  29217. return this._isDirty;
  29218. },
  29219. enumerable: true,
  29220. configurable: true
  29221. });
  29222. MaterialDefines.prototype.markAsProcessed = function () {
  29223. this._isDirty = false;
  29224. this._areAttributesDirty = false;
  29225. this._areTexturesDirty = false;
  29226. this._areFresnelDirty = false;
  29227. this._areLightsDirty = false;
  29228. this._areMiscDirty = false;
  29229. this._areImageProcessingDirty = false;
  29230. };
  29231. MaterialDefines.prototype.markAsUnprocessed = function () {
  29232. this._isDirty = true;
  29233. };
  29234. MaterialDefines.prototype.markAllAsDirty = function () {
  29235. this._areTexturesDirty = true;
  29236. this._areAttributesDirty = true;
  29237. this._areLightsDirty = true;
  29238. this._areFresnelDirty = true;
  29239. this._areMiscDirty = true;
  29240. this._areImageProcessingDirty = true;
  29241. this._isDirty = true;
  29242. };
  29243. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29244. this._areImageProcessingDirty = true;
  29245. this._isDirty = true;
  29246. };
  29247. MaterialDefines.prototype.markAsLightDirty = function () {
  29248. this._areLightsDirty = true;
  29249. this._isDirty = true;
  29250. };
  29251. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29252. this._areAttributesDirty = true;
  29253. this._isDirty = true;
  29254. };
  29255. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29256. this._areTexturesDirty = true;
  29257. this._isDirty = true;
  29258. };
  29259. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29260. this._areFresnelDirty = true;
  29261. this._isDirty = true;
  29262. };
  29263. MaterialDefines.prototype.markAsMiscDirty = function () {
  29264. this._areMiscDirty = true;
  29265. this._isDirty = true;
  29266. };
  29267. MaterialDefines.prototype.rebuild = function () {
  29268. if (this._keys) {
  29269. delete this._keys;
  29270. }
  29271. this._keys = [];
  29272. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29273. var key = _a[_i];
  29274. if (key[0] === "_") {
  29275. continue;
  29276. }
  29277. this._keys.push(key);
  29278. }
  29279. };
  29280. MaterialDefines.prototype.isEqual = function (other) {
  29281. if (this._keys.length !== other._keys.length) {
  29282. return false;
  29283. }
  29284. for (var index = 0; index < this._keys.length; index++) {
  29285. var prop = this._keys[index];
  29286. if (this[prop] !== other[prop]) {
  29287. return false;
  29288. }
  29289. }
  29290. return true;
  29291. };
  29292. MaterialDefines.prototype.cloneTo = function (other) {
  29293. if (this._keys.length !== other._keys.length) {
  29294. other._keys = this._keys.slice(0);
  29295. }
  29296. for (var index = 0; index < this._keys.length; index++) {
  29297. var prop = this._keys[index];
  29298. other[prop] = this[prop];
  29299. }
  29300. };
  29301. MaterialDefines.prototype.reset = function () {
  29302. for (var index = 0; index < this._keys.length; index++) {
  29303. var prop = this._keys[index];
  29304. if (typeof (this[prop]) === "number") {
  29305. this[prop] = 0;
  29306. }
  29307. else {
  29308. this[prop] = false;
  29309. }
  29310. }
  29311. };
  29312. MaterialDefines.prototype.toString = function () {
  29313. var result = "";
  29314. for (var index = 0; index < this._keys.length; index++) {
  29315. var prop = this._keys[index];
  29316. var value = this[prop];
  29317. if (typeof (value) === "number") {
  29318. result += "#define " + prop + " " + this[prop] + "\n";
  29319. }
  29320. else if (value) {
  29321. result += "#define " + prop + "\n";
  29322. }
  29323. }
  29324. return result;
  29325. };
  29326. return MaterialDefines;
  29327. }());
  29328. BABYLON.MaterialDefines = MaterialDefines;
  29329. var Material = /** @class */ (function () {
  29330. function Material(name, scene, doNotAdd) {
  29331. this.checkReadyOnEveryCall = false;
  29332. this.checkReadyOnlyOnce = false;
  29333. this.state = "";
  29334. this._alpha = 1.0;
  29335. this._backFaceCulling = true;
  29336. this.doNotSerialize = false;
  29337. this.storeEffectOnSubMeshes = false;
  29338. /**
  29339. * An event triggered when the material is disposed.
  29340. * @type {BABYLON.Observable}
  29341. */
  29342. this.onDisposeObservable = new BABYLON.Observable();
  29343. /**
  29344. * An event triggered when the material is bound.
  29345. * @type {BABYLON.Observable}
  29346. */
  29347. this.onBindObservable = new BABYLON.Observable();
  29348. /**
  29349. * An event triggered when the material is unbound.
  29350. * @type {BABYLON.Observable}
  29351. */
  29352. this.onUnBindObservable = new BABYLON.Observable();
  29353. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29354. this._needDepthPrePass = false;
  29355. this.disableDepthWrite = false;
  29356. this.forceDepthWrite = false;
  29357. this.separateCullingPass = false;
  29358. this._fogEnabled = true;
  29359. this.pointSize = 1.0;
  29360. this.zOffset = 0;
  29361. this._wasPreviouslyReady = false;
  29362. this._fillMode = Material.TriangleFillMode;
  29363. this.name = name;
  29364. this.id = name || BABYLON.Tools.RandomId();
  29365. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29366. if (this._scene.useRightHandedSystem) {
  29367. this.sideOrientation = Material.ClockWiseSideOrientation;
  29368. }
  29369. else {
  29370. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29371. }
  29372. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29373. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29374. if (!doNotAdd) {
  29375. this._scene.materials.push(this);
  29376. }
  29377. }
  29378. Object.defineProperty(Material, "TriangleFillMode", {
  29379. get: function () {
  29380. return Material._TriangleFillMode;
  29381. },
  29382. enumerable: true,
  29383. configurable: true
  29384. });
  29385. Object.defineProperty(Material, "WireFrameFillMode", {
  29386. get: function () {
  29387. return Material._WireFrameFillMode;
  29388. },
  29389. enumerable: true,
  29390. configurable: true
  29391. });
  29392. Object.defineProperty(Material, "PointFillMode", {
  29393. get: function () {
  29394. return Material._PointFillMode;
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(Material, "PointListDrawMode", {
  29400. get: function () {
  29401. return Material._PointListDrawMode;
  29402. },
  29403. enumerable: true,
  29404. configurable: true
  29405. });
  29406. Object.defineProperty(Material, "LineListDrawMode", {
  29407. get: function () {
  29408. return Material._LineListDrawMode;
  29409. },
  29410. enumerable: true,
  29411. configurable: true
  29412. });
  29413. Object.defineProperty(Material, "LineLoopDrawMode", {
  29414. get: function () {
  29415. return Material._LineLoopDrawMode;
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(Material, "LineStripDrawMode", {
  29421. get: function () {
  29422. return Material._LineStripDrawMode;
  29423. },
  29424. enumerable: true,
  29425. configurable: true
  29426. });
  29427. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29428. get: function () {
  29429. return Material._TriangleStripDrawMode;
  29430. },
  29431. enumerable: true,
  29432. configurable: true
  29433. });
  29434. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29435. get: function () {
  29436. return Material._TriangleFanDrawMode;
  29437. },
  29438. enumerable: true,
  29439. configurable: true
  29440. });
  29441. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29442. get: function () {
  29443. return Material._ClockWiseSideOrientation;
  29444. },
  29445. enumerable: true,
  29446. configurable: true
  29447. });
  29448. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29449. get: function () {
  29450. return Material._CounterClockWiseSideOrientation;
  29451. },
  29452. enumerable: true,
  29453. configurable: true
  29454. });
  29455. Object.defineProperty(Material, "TextureDirtyFlag", {
  29456. get: function () {
  29457. return Material._TextureDirtyFlag;
  29458. },
  29459. enumerable: true,
  29460. configurable: true
  29461. });
  29462. Object.defineProperty(Material, "LightDirtyFlag", {
  29463. get: function () {
  29464. return Material._LightDirtyFlag;
  29465. },
  29466. enumerable: true,
  29467. configurable: true
  29468. });
  29469. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29470. get: function () {
  29471. return Material._FresnelDirtyFlag;
  29472. },
  29473. enumerable: true,
  29474. configurable: true
  29475. });
  29476. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29477. get: function () {
  29478. return Material._AttributesDirtyFlag;
  29479. },
  29480. enumerable: true,
  29481. configurable: true
  29482. });
  29483. Object.defineProperty(Material, "MiscDirtyFlag", {
  29484. get: function () {
  29485. return Material._MiscDirtyFlag;
  29486. },
  29487. enumerable: true,
  29488. configurable: true
  29489. });
  29490. Object.defineProperty(Material.prototype, "alpha", {
  29491. get: function () {
  29492. return this._alpha;
  29493. },
  29494. set: function (value) {
  29495. if (this._alpha === value) {
  29496. return;
  29497. }
  29498. this._alpha = value;
  29499. this.markAsDirty(Material.MiscDirtyFlag);
  29500. },
  29501. enumerable: true,
  29502. configurable: true
  29503. });
  29504. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29505. get: function () {
  29506. return this._backFaceCulling;
  29507. },
  29508. set: function (value) {
  29509. if (this._backFaceCulling === value) {
  29510. return;
  29511. }
  29512. this._backFaceCulling = value;
  29513. this.markAsDirty(Material.TextureDirtyFlag);
  29514. },
  29515. enumerable: true,
  29516. configurable: true
  29517. });
  29518. Object.defineProperty(Material.prototype, "onDispose", {
  29519. set: function (callback) {
  29520. if (this._onDisposeObserver) {
  29521. this.onDisposeObservable.remove(this._onDisposeObserver);
  29522. }
  29523. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29524. },
  29525. enumerable: true,
  29526. configurable: true
  29527. });
  29528. Object.defineProperty(Material.prototype, "onBind", {
  29529. set: function (callback) {
  29530. if (this._onBindObserver) {
  29531. this.onBindObservable.remove(this._onBindObserver);
  29532. }
  29533. this._onBindObserver = this.onBindObservable.add(callback);
  29534. },
  29535. enumerable: true,
  29536. configurable: true
  29537. });
  29538. Object.defineProperty(Material.prototype, "alphaMode", {
  29539. get: function () {
  29540. return this._alphaMode;
  29541. },
  29542. set: function (value) {
  29543. if (this._alphaMode === value) {
  29544. return;
  29545. }
  29546. this._alphaMode = value;
  29547. this.markAsDirty(Material.TextureDirtyFlag);
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29553. get: function () {
  29554. return this._needDepthPrePass;
  29555. },
  29556. set: function (value) {
  29557. if (this._needDepthPrePass === value) {
  29558. return;
  29559. }
  29560. this._needDepthPrePass = value;
  29561. if (this._needDepthPrePass) {
  29562. this.checkReadyOnEveryCall = true;
  29563. }
  29564. },
  29565. enumerable: true,
  29566. configurable: true
  29567. });
  29568. Object.defineProperty(Material.prototype, "fogEnabled", {
  29569. get: function () {
  29570. return this._fogEnabled;
  29571. },
  29572. set: function (value) {
  29573. if (this._fogEnabled === value) {
  29574. return;
  29575. }
  29576. this._fogEnabled = value;
  29577. this.markAsDirty(Material.MiscDirtyFlag);
  29578. },
  29579. enumerable: true,
  29580. configurable: true
  29581. });
  29582. Object.defineProperty(Material.prototype, "wireframe", {
  29583. get: function () {
  29584. return this._fillMode === Material.WireFrameFillMode;
  29585. },
  29586. set: function (value) {
  29587. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29588. },
  29589. enumerable: true,
  29590. configurable: true
  29591. });
  29592. Object.defineProperty(Material.prototype, "pointsCloud", {
  29593. get: function () {
  29594. return this._fillMode === Material.PointFillMode;
  29595. },
  29596. set: function (value) {
  29597. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29598. },
  29599. enumerable: true,
  29600. configurable: true
  29601. });
  29602. Object.defineProperty(Material.prototype, "fillMode", {
  29603. get: function () {
  29604. return this._fillMode;
  29605. },
  29606. set: function (value) {
  29607. if (this._fillMode === value) {
  29608. return;
  29609. }
  29610. this._fillMode = value;
  29611. this.markAsDirty(Material.MiscDirtyFlag);
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. /**
  29617. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29618. * subclasses should override adding information pertainent to themselves
  29619. */
  29620. Material.prototype.toString = function (fullDetails) {
  29621. var ret = "Name: " + this.name;
  29622. if (fullDetails) {
  29623. }
  29624. return ret;
  29625. };
  29626. /**
  29627. * Child classes can use it to update shaders
  29628. */
  29629. Material.prototype.getClassName = function () {
  29630. return "Material";
  29631. };
  29632. Object.defineProperty(Material.prototype, "isFrozen", {
  29633. get: function () {
  29634. return this.checkReadyOnlyOnce;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. Material.prototype.freeze = function () {
  29640. this.checkReadyOnlyOnce = true;
  29641. };
  29642. Material.prototype.unfreeze = function () {
  29643. this.checkReadyOnlyOnce = false;
  29644. };
  29645. Material.prototype.isReady = function (mesh, useInstances) {
  29646. return true;
  29647. };
  29648. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29649. return false;
  29650. };
  29651. Material.prototype.getEffect = function () {
  29652. return this._effect;
  29653. };
  29654. Material.prototype.getScene = function () {
  29655. return this._scene;
  29656. };
  29657. Material.prototype.needAlphaBlending = function () {
  29658. return (this.alpha < 1.0);
  29659. };
  29660. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29661. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29662. };
  29663. Material.prototype.needAlphaTesting = function () {
  29664. return false;
  29665. };
  29666. Material.prototype.getAlphaTestTexture = function () {
  29667. return null;
  29668. };
  29669. Material.prototype.markDirty = function () {
  29670. this._wasPreviouslyReady = false;
  29671. };
  29672. Material.prototype._preBind = function (effect, overrideOrientation) {
  29673. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29674. var engine = this._scene.getEngine();
  29675. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29676. var reverse = orientation === Material.ClockWiseSideOrientation;
  29677. engine.enableEffect(effect ? effect : this._effect);
  29678. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29679. return reverse;
  29680. };
  29681. Material.prototype.bind = function (world, mesh) {
  29682. };
  29683. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29684. };
  29685. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29686. };
  29687. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29688. sceneUbo.bindToEffect(effect, "Scene");
  29689. };
  29690. Material.prototype.bindView = function (effect) {
  29691. if (!this._useUBO) {
  29692. effect.setMatrix("view", this.getScene().getViewMatrix());
  29693. }
  29694. else {
  29695. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29696. }
  29697. };
  29698. Material.prototype.bindViewProjection = function (effect) {
  29699. if (!this._useUBO) {
  29700. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29701. }
  29702. else {
  29703. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29704. }
  29705. };
  29706. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29707. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29708. };
  29709. Material.prototype._afterBind = function (mesh) {
  29710. this._scene._cachedMaterial = this;
  29711. if (mesh) {
  29712. this._scene._cachedVisibility = mesh.visibility;
  29713. }
  29714. else {
  29715. this._scene._cachedVisibility = 1;
  29716. }
  29717. if (mesh) {
  29718. this.onBindObservable.notifyObservers(mesh);
  29719. }
  29720. if (this.disableDepthWrite) {
  29721. var engine = this._scene.getEngine();
  29722. this._cachedDepthWriteState = engine.getDepthWrite();
  29723. engine.setDepthWrite(false);
  29724. }
  29725. };
  29726. Material.prototype.unbind = function () {
  29727. this.onUnBindObservable.notifyObservers(this);
  29728. if (this.disableDepthWrite) {
  29729. var engine = this._scene.getEngine();
  29730. engine.setDepthWrite(this._cachedDepthWriteState);
  29731. }
  29732. };
  29733. Material.prototype.getActiveTextures = function () {
  29734. return [];
  29735. };
  29736. Material.prototype.hasTexture = function (texture) {
  29737. return false;
  29738. };
  29739. Material.prototype.clone = function (name) {
  29740. return null;
  29741. };
  29742. Material.prototype.getBindedMeshes = function () {
  29743. var result = new Array();
  29744. for (var index = 0; index < this._scene.meshes.length; index++) {
  29745. var mesh = this._scene.meshes[index];
  29746. if (mesh.material === this) {
  29747. result.push(mesh);
  29748. }
  29749. }
  29750. return result;
  29751. };
  29752. /**
  29753. * Force shader compilation including textures ready check
  29754. */
  29755. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29756. var _this = this;
  29757. var localOptions = __assign({ clipPlane: false }, options);
  29758. var subMesh = new BABYLON.BaseSubMesh();
  29759. var scene = this.getScene();
  29760. var checkReady = function () {
  29761. if (!_this._scene || !_this._scene.getEngine()) {
  29762. return;
  29763. }
  29764. if (subMesh._materialDefines) {
  29765. subMesh._materialDefines._renderId = -1;
  29766. }
  29767. var clipPlaneState = scene.clipPlane;
  29768. if (localOptions.clipPlane) {
  29769. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29770. }
  29771. if (_this.storeEffectOnSubMeshes) {
  29772. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29773. if (onCompiled) {
  29774. onCompiled(_this);
  29775. }
  29776. }
  29777. else {
  29778. setTimeout(checkReady, 16);
  29779. }
  29780. }
  29781. else {
  29782. if (_this.isReady(mesh)) {
  29783. if (onCompiled) {
  29784. onCompiled(_this);
  29785. }
  29786. }
  29787. else {
  29788. setTimeout(checkReady, 16);
  29789. }
  29790. }
  29791. if (options && options.clipPlane) {
  29792. scene.clipPlane = clipPlaneState;
  29793. }
  29794. };
  29795. checkReady();
  29796. };
  29797. Material.prototype.markAsDirty = function (flag) {
  29798. if (flag & Material.TextureDirtyFlag) {
  29799. this._markAllSubMeshesAsTexturesDirty();
  29800. }
  29801. if (flag & Material.LightDirtyFlag) {
  29802. this._markAllSubMeshesAsLightsDirty();
  29803. }
  29804. if (flag & Material.FresnelDirtyFlag) {
  29805. this._markAllSubMeshesAsFresnelDirty();
  29806. }
  29807. if (flag & Material.AttributesDirtyFlag) {
  29808. this._markAllSubMeshesAsAttributesDirty();
  29809. }
  29810. if (flag & Material.MiscDirtyFlag) {
  29811. this._markAllSubMeshesAsMiscDirty();
  29812. }
  29813. this.getScene().resetCachedMaterial();
  29814. };
  29815. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29816. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29817. var mesh = _a[_i];
  29818. if (!mesh.subMeshes) {
  29819. continue;
  29820. }
  29821. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29822. var subMesh = _c[_b];
  29823. if (subMesh.getMaterial() !== this) {
  29824. continue;
  29825. }
  29826. if (!subMesh._materialDefines) {
  29827. continue;
  29828. }
  29829. func(subMesh._materialDefines);
  29830. }
  29831. }
  29832. };
  29833. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29834. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29835. };
  29836. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29837. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29838. };
  29839. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29840. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29841. };
  29842. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29843. this._markAllSubMeshesAsDirty(function (defines) {
  29844. defines.markAsFresnelDirty();
  29845. defines.markAsMiscDirty();
  29846. });
  29847. };
  29848. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29849. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29850. };
  29851. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29852. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29853. };
  29854. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29855. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29856. };
  29857. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29858. this._markAllSubMeshesAsDirty(function (defines) {
  29859. defines.markAsTexturesDirty();
  29860. defines.markAsMiscDirty();
  29861. });
  29862. };
  29863. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29864. // Animations
  29865. this.getScene().stopAnimation(this);
  29866. // Remove from scene
  29867. var index = this._scene.materials.indexOf(this);
  29868. if (index >= 0) {
  29869. this._scene.materials.splice(index, 1);
  29870. }
  29871. // Remove from meshes
  29872. for (index = 0; index < this._scene.meshes.length; index++) {
  29873. var mesh = this._scene.meshes[index];
  29874. if (mesh.material === this) {
  29875. mesh.material = null;
  29876. if (mesh.geometry) {
  29877. var geometry = (mesh.geometry);
  29878. if (this.storeEffectOnSubMeshes) {
  29879. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29880. var subMesh = _a[_i];
  29881. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29882. if (forceDisposeEffect && subMesh._materialEffect) {
  29883. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29884. }
  29885. }
  29886. }
  29887. else {
  29888. geometry._releaseVertexArrayObject(this._effect);
  29889. }
  29890. }
  29891. }
  29892. }
  29893. this._uniformBuffer.dispose();
  29894. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29895. if (forceDisposeEffect && this._effect) {
  29896. if (!this.storeEffectOnSubMeshes) {
  29897. this._scene.getEngine()._releaseEffect(this._effect);
  29898. }
  29899. this._effect = null;
  29900. }
  29901. // Callback
  29902. this.onDisposeObservable.notifyObservers(this);
  29903. this.onDisposeObservable.clear();
  29904. this.onBindObservable.clear();
  29905. this.onUnBindObservable.clear();
  29906. };
  29907. Material.prototype.serialize = function () {
  29908. return BABYLON.SerializationHelper.Serialize(this);
  29909. };
  29910. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29911. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29912. multiMaterial.id = parsedMultiMaterial.id;
  29913. if (BABYLON.Tags) {
  29914. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29915. }
  29916. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29917. var subMatId = parsedMultiMaterial.materials[matIndex];
  29918. if (subMatId) {
  29919. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29920. }
  29921. else {
  29922. multiMaterial.subMaterials.push(null);
  29923. }
  29924. }
  29925. return multiMaterial;
  29926. };
  29927. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29928. if (!parsedMaterial.customType) {
  29929. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29930. }
  29931. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29932. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29933. if (!BABYLON.LegacyPBRMaterial) {
  29934. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29935. return;
  29936. }
  29937. }
  29938. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29939. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29940. ;
  29941. };
  29942. // Triangle views
  29943. Material._TriangleFillMode = 0;
  29944. Material._WireFrameFillMode = 1;
  29945. Material._PointFillMode = 2;
  29946. // Draw modes
  29947. Material._PointListDrawMode = 3;
  29948. Material._LineListDrawMode = 4;
  29949. Material._LineLoopDrawMode = 5;
  29950. Material._LineStripDrawMode = 6;
  29951. Material._TriangleStripDrawMode = 7;
  29952. Material._TriangleFanDrawMode = 8;
  29953. Material._ClockWiseSideOrientation = 0;
  29954. Material._CounterClockWiseSideOrientation = 1;
  29955. Material._TextureDirtyFlag = 1;
  29956. Material._LightDirtyFlag = 2;
  29957. Material._FresnelDirtyFlag = 4;
  29958. Material._AttributesDirtyFlag = 8;
  29959. Material._MiscDirtyFlag = 16;
  29960. __decorate([
  29961. BABYLON.serialize()
  29962. ], Material.prototype, "id", void 0);
  29963. __decorate([
  29964. BABYLON.serialize()
  29965. ], Material.prototype, "name", void 0);
  29966. __decorate([
  29967. BABYLON.serialize()
  29968. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29969. __decorate([
  29970. BABYLON.serialize()
  29971. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29972. __decorate([
  29973. BABYLON.serialize()
  29974. ], Material.prototype, "state", void 0);
  29975. __decorate([
  29976. BABYLON.serialize("alpha")
  29977. ], Material.prototype, "_alpha", void 0);
  29978. __decorate([
  29979. BABYLON.serialize("backFaceCulling")
  29980. ], Material.prototype, "_backFaceCulling", void 0);
  29981. __decorate([
  29982. BABYLON.serialize()
  29983. ], Material.prototype, "sideOrientation", void 0);
  29984. __decorate([
  29985. BABYLON.serialize("alphaMode")
  29986. ], Material.prototype, "_alphaMode", void 0);
  29987. __decorate([
  29988. BABYLON.serialize()
  29989. ], Material.prototype, "_needDepthPrePass", void 0);
  29990. __decorate([
  29991. BABYLON.serialize()
  29992. ], Material.prototype, "disableDepthWrite", void 0);
  29993. __decorate([
  29994. BABYLON.serialize()
  29995. ], Material.prototype, "forceDepthWrite", void 0);
  29996. __decorate([
  29997. BABYLON.serialize()
  29998. ], Material.prototype, "separateCullingPass", void 0);
  29999. __decorate([
  30000. BABYLON.serialize("fogEnabled")
  30001. ], Material.prototype, "_fogEnabled", void 0);
  30002. __decorate([
  30003. BABYLON.serialize()
  30004. ], Material.prototype, "pointSize", void 0);
  30005. __decorate([
  30006. BABYLON.serialize()
  30007. ], Material.prototype, "zOffset", void 0);
  30008. __decorate([
  30009. BABYLON.serialize()
  30010. ], Material.prototype, "wireframe", null);
  30011. __decorate([
  30012. BABYLON.serialize()
  30013. ], Material.prototype, "pointsCloud", null);
  30014. __decorate([
  30015. BABYLON.serialize()
  30016. ], Material.prototype, "fillMode", null);
  30017. return Material;
  30018. }());
  30019. BABYLON.Material = Material;
  30020. })(BABYLON || (BABYLON = {}));
  30021. //# sourceMappingURL=babylon.material.js.map
  30022. var BABYLON;
  30023. (function (BABYLON) {
  30024. var UniformBuffer = /** @class */ (function () {
  30025. /**
  30026. * Uniform buffer objects.
  30027. *
  30028. * Handles blocks of uniform on the GPU.
  30029. *
  30030. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  30031. *
  30032. * For more information, please refer to :
  30033. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  30034. */
  30035. function UniformBuffer(engine, data, dynamic) {
  30036. this._engine = engine;
  30037. this._noUBO = !engine.supportsUniformBuffers;
  30038. this._dynamic = dynamic;
  30039. this._data = data || [];
  30040. this._uniformLocations = {};
  30041. this._uniformSizes = {};
  30042. this._uniformLocationPointer = 0;
  30043. this._needSync = false;
  30044. if (this._noUBO) {
  30045. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  30046. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  30047. this.updateFloat = this._updateFloatForEffect;
  30048. this.updateFloat2 = this._updateFloat2ForEffect;
  30049. this.updateFloat3 = this._updateFloat3ForEffect;
  30050. this.updateFloat4 = this._updateFloat4ForEffect;
  30051. this.updateMatrix = this._updateMatrixForEffect;
  30052. this.updateVector3 = this._updateVector3ForEffect;
  30053. this.updateVector4 = this._updateVector4ForEffect;
  30054. this.updateColor3 = this._updateColor3ForEffect;
  30055. this.updateColor4 = this._updateColor4ForEffect;
  30056. }
  30057. else {
  30058. this._engine._uniformBuffers.push(this);
  30059. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  30060. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  30061. this.updateFloat = this._updateFloatForUniform;
  30062. this.updateFloat2 = this._updateFloat2ForUniform;
  30063. this.updateFloat3 = this._updateFloat3ForUniform;
  30064. this.updateFloat4 = this._updateFloat4ForUniform;
  30065. this.updateMatrix = this._updateMatrixForUniform;
  30066. this.updateVector3 = this._updateVector3ForUniform;
  30067. this.updateVector4 = this._updateVector4ForUniform;
  30068. this.updateColor3 = this._updateColor3ForUniform;
  30069. this.updateColor4 = this._updateColor4ForUniform;
  30070. }
  30071. }
  30072. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  30073. // Properties
  30074. /**
  30075. * Indicates if the buffer is using the WebGL2 UBO implementation,
  30076. * or just falling back on setUniformXXX calls.
  30077. */
  30078. get: function () {
  30079. return !this._noUBO;
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  30085. /**
  30086. * Indicates if the WebGL underlying uniform buffer is in sync
  30087. * with the javascript cache data.
  30088. */
  30089. get: function () {
  30090. return !this._needSync;
  30091. },
  30092. enumerable: true,
  30093. configurable: true
  30094. });
  30095. /**
  30096. * Indicates if the WebGL underlying uniform buffer is dynamic.
  30097. * Also, a dynamic UniformBuffer will disable cache verification and always
  30098. * update the underlying WebGL uniform buffer to the GPU.
  30099. */
  30100. UniformBuffer.prototype.isDynamic = function () {
  30101. return this._dynamic !== undefined;
  30102. };
  30103. /**
  30104. * The data cache on JS side.
  30105. */
  30106. UniformBuffer.prototype.getData = function () {
  30107. return this._bufferData;
  30108. };
  30109. /**
  30110. * The underlying WebGL Uniform buffer.
  30111. */
  30112. UniformBuffer.prototype.getBuffer = function () {
  30113. return this._buffer;
  30114. };
  30115. /**
  30116. * std140 layout specifies how to align data within an UBO structure.
  30117. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  30118. * for specs.
  30119. */
  30120. UniformBuffer.prototype._fillAlignment = function (size) {
  30121. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  30122. // and 4x4 matrices
  30123. // TODO : change if other types are used
  30124. var alignment;
  30125. if (size <= 2) {
  30126. alignment = size;
  30127. }
  30128. else {
  30129. alignment = 4;
  30130. }
  30131. if ((this._uniformLocationPointer % alignment) !== 0) {
  30132. var oldPointer = this._uniformLocationPointer;
  30133. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  30134. var diff = this._uniformLocationPointer - oldPointer;
  30135. for (var i = 0; i < diff; i++) {
  30136. this._data.push(0);
  30137. }
  30138. }
  30139. };
  30140. /**
  30141. * Adds an uniform in the buffer.
  30142. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  30143. * for the layout to be correct !
  30144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30145. * @param {number|number[]} size Data size, or data directly.
  30146. */
  30147. UniformBuffer.prototype.addUniform = function (name, size) {
  30148. if (this._noUBO) {
  30149. return;
  30150. }
  30151. if (this._uniformLocations[name] !== undefined) {
  30152. // Already existing uniform
  30153. return;
  30154. }
  30155. // This function must be called in the order of the shader layout !
  30156. // size can be the size of the uniform, or data directly
  30157. var data;
  30158. if (size instanceof Array) {
  30159. data = size;
  30160. size = data.length;
  30161. }
  30162. else {
  30163. size = size;
  30164. data = [];
  30165. // Fill with zeros
  30166. for (var i = 0; i < size; i++) {
  30167. data.push(0);
  30168. }
  30169. }
  30170. this._fillAlignment(size);
  30171. this._uniformSizes[name] = size;
  30172. this._uniformLocations[name] = this._uniformLocationPointer;
  30173. this._uniformLocationPointer += size;
  30174. for (var i = 0; i < size; i++) {
  30175. this._data.push(data[i]);
  30176. }
  30177. this._needSync = true;
  30178. };
  30179. /**
  30180. * Wrapper for addUniform.
  30181. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30182. * @param {Matrix} mat A 4x4 matrix.
  30183. */
  30184. UniformBuffer.prototype.addMatrix = function (name, mat) {
  30185. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  30186. };
  30187. /**
  30188. * Wrapper for addUniform.
  30189. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30190. * @param {number} x
  30191. * @param {number} y
  30192. */
  30193. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  30194. var temp = [x, y];
  30195. this.addUniform(name, temp);
  30196. };
  30197. /**
  30198. * Wrapper for addUniform.
  30199. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30200. * @param {number} x
  30201. * @param {number} y
  30202. * @param {number} z
  30203. */
  30204. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  30205. var temp = [x, y, z];
  30206. this.addUniform(name, temp);
  30207. };
  30208. /**
  30209. * Wrapper for addUniform.
  30210. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30211. * @param {Color3} color
  30212. */
  30213. UniformBuffer.prototype.addColor3 = function (name, color) {
  30214. var temp = new Array();
  30215. color.toArray(temp);
  30216. this.addUniform(name, temp);
  30217. };
  30218. /**
  30219. * Wrapper for addUniform.
  30220. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30221. * @param {Color3} color
  30222. * @param {number} alpha
  30223. */
  30224. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  30225. var temp = new Array();
  30226. color.toArray(temp);
  30227. temp.push(alpha);
  30228. this.addUniform(name, temp);
  30229. };
  30230. /**
  30231. * Wrapper for addUniform.
  30232. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30233. * @param {Vector3} vector
  30234. */
  30235. UniformBuffer.prototype.addVector3 = function (name, vector) {
  30236. var temp = new Array();
  30237. vector.toArray(temp);
  30238. this.addUniform(name, temp);
  30239. };
  30240. /**
  30241. * Wrapper for addUniform.
  30242. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30243. */
  30244. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  30245. this.addUniform(name, 12);
  30246. };
  30247. /**
  30248. * Wrapper for addUniform.
  30249. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30250. */
  30251. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30252. this.addUniform(name, 8);
  30253. };
  30254. /**
  30255. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30256. */
  30257. UniformBuffer.prototype.create = function () {
  30258. if (this._noUBO) {
  30259. return;
  30260. }
  30261. if (this._buffer) {
  30262. return; // nothing to do
  30263. }
  30264. // See spec, alignment must be filled as a vec4
  30265. this._fillAlignment(4);
  30266. this._bufferData = new Float32Array(this._data);
  30267. this._rebuild();
  30268. this._needSync = true;
  30269. };
  30270. UniformBuffer.prototype._rebuild = function () {
  30271. if (this._noUBO) {
  30272. return;
  30273. }
  30274. if (this._dynamic) {
  30275. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30276. }
  30277. else {
  30278. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30279. }
  30280. };
  30281. /**
  30282. * Updates the WebGL Uniform Buffer on the GPU.
  30283. * If the `dynamic` flag is set to true, no cache comparison is done.
  30284. * Otherwise, the buffer will be updated only if the cache differs.
  30285. */
  30286. UniformBuffer.prototype.update = function () {
  30287. if (!this._buffer) {
  30288. this.create();
  30289. return;
  30290. }
  30291. if (!this._dynamic && !this._needSync) {
  30292. return;
  30293. }
  30294. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30295. this._needSync = false;
  30296. };
  30297. /**
  30298. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30299. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30300. * @param {number[]|Float32Array} data Flattened data
  30301. * @param {number} size Size of the data.
  30302. */
  30303. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30304. var location = this._uniformLocations[uniformName];
  30305. if (location === undefined) {
  30306. if (this._buffer) {
  30307. // Cannot add an uniform if the buffer is already created
  30308. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30309. return;
  30310. }
  30311. this.addUniform(uniformName, size);
  30312. location = this._uniformLocations[uniformName];
  30313. }
  30314. if (!this._buffer) {
  30315. this.create();
  30316. }
  30317. if (!this._dynamic) {
  30318. // Cache for static uniform buffers
  30319. var changed = false;
  30320. for (var i = 0; i < size; i++) {
  30321. if (this._bufferData[location + i] !== data[i]) {
  30322. changed = true;
  30323. this._bufferData[location + i] = data[i];
  30324. }
  30325. }
  30326. this._needSync = this._needSync || changed;
  30327. }
  30328. else {
  30329. // No cache for dynamic
  30330. for (var i = 0; i < size; i++) {
  30331. this._bufferData[location + i] = data[i];
  30332. }
  30333. }
  30334. };
  30335. // Update methods
  30336. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30337. // To match std140, matrix must be realigned
  30338. for (var i = 0; i < 3; i++) {
  30339. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30340. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30341. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30342. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30343. }
  30344. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30345. };
  30346. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30347. this._currentEffect.setMatrix3x3(name, matrix);
  30348. };
  30349. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30350. this._currentEffect.setMatrix2x2(name, matrix);
  30351. };
  30352. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30353. // To match std140, matrix must be realigned
  30354. for (var i = 0; i < 2; i++) {
  30355. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30356. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30357. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30358. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30359. }
  30360. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30361. };
  30362. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30363. this._currentEffect.setFloat(name, x);
  30364. };
  30365. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30366. UniformBuffer._tempBuffer[0] = x;
  30367. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30368. };
  30369. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30370. if (suffix === void 0) { suffix = ""; }
  30371. this._currentEffect.setFloat2(name + suffix, x, y);
  30372. };
  30373. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30374. if (suffix === void 0) { suffix = ""; }
  30375. UniformBuffer._tempBuffer[0] = x;
  30376. UniformBuffer._tempBuffer[1] = y;
  30377. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30378. };
  30379. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30380. if (suffix === void 0) { suffix = ""; }
  30381. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30382. };
  30383. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30384. if (suffix === void 0) { suffix = ""; }
  30385. UniformBuffer._tempBuffer[0] = x;
  30386. UniformBuffer._tempBuffer[1] = y;
  30387. UniformBuffer._tempBuffer[2] = z;
  30388. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30389. };
  30390. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30391. if (suffix === void 0) { suffix = ""; }
  30392. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30393. };
  30394. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30395. if (suffix === void 0) { suffix = ""; }
  30396. UniformBuffer._tempBuffer[0] = x;
  30397. UniformBuffer._tempBuffer[1] = y;
  30398. UniformBuffer._tempBuffer[2] = z;
  30399. UniformBuffer._tempBuffer[3] = w;
  30400. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30401. };
  30402. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30403. this._currentEffect.setMatrix(name, mat);
  30404. };
  30405. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30406. this.updateUniform(name, mat.toArray(), 16);
  30407. };
  30408. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30409. this._currentEffect.setVector3(name, vector);
  30410. };
  30411. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30412. vector.toArray(UniformBuffer._tempBuffer);
  30413. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30414. };
  30415. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30416. this._currentEffect.setVector4(name, vector);
  30417. };
  30418. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30419. vector.toArray(UniformBuffer._tempBuffer);
  30420. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30421. };
  30422. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30423. if (suffix === void 0) { suffix = ""; }
  30424. this._currentEffect.setColor3(name + suffix, color);
  30425. };
  30426. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30427. if (suffix === void 0) { suffix = ""; }
  30428. color.toArray(UniformBuffer._tempBuffer);
  30429. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30430. };
  30431. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30432. if (suffix === void 0) { suffix = ""; }
  30433. this._currentEffect.setColor4(name + suffix, color, alpha);
  30434. };
  30435. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30436. if (suffix === void 0) { suffix = ""; }
  30437. color.toArray(UniformBuffer._tempBuffer);
  30438. UniformBuffer._tempBuffer[3] = alpha;
  30439. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30440. };
  30441. /**
  30442. * Sets a sampler uniform on the effect.
  30443. * @param {string} name Name of the sampler.
  30444. * @param {Texture} texture
  30445. */
  30446. UniformBuffer.prototype.setTexture = function (name, texture) {
  30447. this._currentEffect.setTexture(name, texture);
  30448. };
  30449. /**
  30450. * Directly updates the value of the uniform in the cache AND on the GPU.
  30451. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30452. * @param {number[]|Float32Array} data Flattened data
  30453. */
  30454. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30455. this.updateUniform(uniformName, data, data.length);
  30456. this.update();
  30457. };
  30458. /**
  30459. * Binds this uniform buffer to an effect.
  30460. * @param {Effect} effect
  30461. * @param {string} name Name of the uniform block in the shader.
  30462. */
  30463. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30464. this._currentEffect = effect;
  30465. if (this._noUBO || !this._buffer) {
  30466. return;
  30467. }
  30468. effect.bindUniformBuffer(this._buffer, name);
  30469. };
  30470. /**
  30471. * Disposes the uniform buffer.
  30472. */
  30473. UniformBuffer.prototype.dispose = function () {
  30474. if (this._noUBO) {
  30475. return;
  30476. }
  30477. var index = this._engine._uniformBuffers.indexOf(this);
  30478. if (index !== -1) {
  30479. this._engine._uniformBuffers.splice(index, 1);
  30480. }
  30481. if (!this._buffer) {
  30482. return;
  30483. }
  30484. if (this._engine._releaseBuffer(this._buffer)) {
  30485. this._buffer = null;
  30486. }
  30487. };
  30488. // Pool for avoiding memory leaks
  30489. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30490. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30491. return UniformBuffer;
  30492. }());
  30493. BABYLON.UniformBuffer = UniformBuffer;
  30494. })(BABYLON || (BABYLON = {}));
  30495. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30496. var BABYLON;
  30497. (function (BABYLON) {
  30498. var VertexData = /** @class */ (function () {
  30499. function VertexData() {
  30500. }
  30501. VertexData.prototype.set = function (data, kind) {
  30502. switch (kind) {
  30503. case BABYLON.VertexBuffer.PositionKind:
  30504. this.positions = data;
  30505. break;
  30506. case BABYLON.VertexBuffer.NormalKind:
  30507. this.normals = data;
  30508. break;
  30509. case BABYLON.VertexBuffer.TangentKind:
  30510. this.tangents = data;
  30511. break;
  30512. case BABYLON.VertexBuffer.UVKind:
  30513. this.uvs = data;
  30514. break;
  30515. case BABYLON.VertexBuffer.UV2Kind:
  30516. this.uvs2 = data;
  30517. break;
  30518. case BABYLON.VertexBuffer.UV3Kind:
  30519. this.uvs3 = data;
  30520. break;
  30521. case BABYLON.VertexBuffer.UV4Kind:
  30522. this.uvs4 = data;
  30523. break;
  30524. case BABYLON.VertexBuffer.UV5Kind:
  30525. this.uvs5 = data;
  30526. break;
  30527. case BABYLON.VertexBuffer.UV6Kind:
  30528. this.uvs6 = data;
  30529. break;
  30530. case BABYLON.VertexBuffer.ColorKind:
  30531. this.colors = data;
  30532. break;
  30533. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30534. this.matricesIndices = data;
  30535. break;
  30536. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30537. this.matricesWeights = data;
  30538. break;
  30539. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30540. this.matricesIndicesExtra = data;
  30541. break;
  30542. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30543. this.matricesWeightsExtra = data;
  30544. break;
  30545. }
  30546. };
  30547. /**
  30548. * Associates the vertexData to the passed Mesh.
  30549. * Sets it as updatable or not (default `false`).
  30550. * Returns the VertexData.
  30551. */
  30552. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30553. this._applyTo(mesh, updatable);
  30554. return this;
  30555. };
  30556. /**
  30557. * Associates the vertexData to the passed Geometry.
  30558. * Sets it as updatable or not (default `false`).
  30559. * Returns the VertexData.
  30560. */
  30561. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30562. this._applyTo(geometry, updatable);
  30563. return this;
  30564. };
  30565. /**
  30566. * Updates the associated mesh.
  30567. * Returns the VertexData.
  30568. */
  30569. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30570. this._update(mesh);
  30571. return this;
  30572. };
  30573. /**
  30574. * Updates the associated geometry.
  30575. * Returns the VertexData.
  30576. */
  30577. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30578. this._update(geometry);
  30579. return this;
  30580. };
  30581. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30582. if (updatable === void 0) { updatable = false; }
  30583. if (this.positions) {
  30584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30585. }
  30586. if (this.normals) {
  30587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30588. }
  30589. if (this.tangents) {
  30590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30591. }
  30592. if (this.uvs) {
  30593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30594. }
  30595. if (this.uvs2) {
  30596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30597. }
  30598. if (this.uvs3) {
  30599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30600. }
  30601. if (this.uvs4) {
  30602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30603. }
  30604. if (this.uvs5) {
  30605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30606. }
  30607. if (this.uvs6) {
  30608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30609. }
  30610. if (this.colors) {
  30611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30612. }
  30613. if (this.matricesIndices) {
  30614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30615. }
  30616. if (this.matricesWeights) {
  30617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30618. }
  30619. if (this.matricesIndicesExtra) {
  30620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30621. }
  30622. if (this.matricesWeightsExtra) {
  30623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30624. }
  30625. if (this.indices) {
  30626. meshOrGeometry.setIndices(this.indices, null, updatable);
  30627. }
  30628. return this;
  30629. };
  30630. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30631. if (this.positions) {
  30632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30633. }
  30634. if (this.normals) {
  30635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30636. }
  30637. if (this.tangents) {
  30638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30639. }
  30640. if (this.uvs) {
  30641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30642. }
  30643. if (this.uvs2) {
  30644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30645. }
  30646. if (this.uvs3) {
  30647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30648. }
  30649. if (this.uvs4) {
  30650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30651. }
  30652. if (this.uvs5) {
  30653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30654. }
  30655. if (this.uvs6) {
  30656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30657. }
  30658. if (this.colors) {
  30659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30660. }
  30661. if (this.matricesIndices) {
  30662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30663. }
  30664. if (this.matricesWeights) {
  30665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30666. }
  30667. if (this.matricesIndicesExtra) {
  30668. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30669. }
  30670. if (this.matricesWeightsExtra) {
  30671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30672. }
  30673. if (this.indices) {
  30674. meshOrGeometry.setIndices(this.indices, null);
  30675. }
  30676. return this;
  30677. };
  30678. /**
  30679. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30680. * Returns the VertexData.
  30681. */
  30682. VertexData.prototype.transform = function (matrix) {
  30683. var transformed = BABYLON.Vector3.Zero();
  30684. var index;
  30685. if (this.positions) {
  30686. var position = BABYLON.Vector3.Zero();
  30687. for (index = 0; index < this.positions.length; index += 3) {
  30688. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30689. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30690. this.positions[index] = transformed.x;
  30691. this.positions[index + 1] = transformed.y;
  30692. this.positions[index + 2] = transformed.z;
  30693. }
  30694. }
  30695. if (this.normals) {
  30696. var normal = BABYLON.Vector3.Zero();
  30697. for (index = 0; index < this.normals.length; index += 3) {
  30698. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30699. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30700. this.normals[index] = transformed.x;
  30701. this.normals[index + 1] = transformed.y;
  30702. this.normals[index + 2] = transformed.z;
  30703. }
  30704. }
  30705. if (this.tangents) {
  30706. var tangent = BABYLON.Vector4.Zero();
  30707. var tangentTransformed = BABYLON.Vector4.Zero();
  30708. for (index = 0; index < this.tangents.length; index += 4) {
  30709. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30710. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30711. this.tangents[index] = tangentTransformed.x;
  30712. this.tangents[index + 1] = tangentTransformed.y;
  30713. this.tangents[index + 2] = tangentTransformed.z;
  30714. this.tangents[index + 3] = tangentTransformed.w;
  30715. }
  30716. }
  30717. return this;
  30718. };
  30719. /**
  30720. * Merges the passed VertexData into the current one.
  30721. * Returns the modified VertexData.
  30722. */
  30723. VertexData.prototype.merge = function (other, options) {
  30724. options = options || {};
  30725. if (other.indices) {
  30726. if (!this.indices) {
  30727. this.indices = [];
  30728. }
  30729. var offset = this.positions ? this.positions.length / 3 : 0;
  30730. for (var index = 0; index < other.indices.length; index++) {
  30731. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30732. this.indices.push(other.indices[index] + offset);
  30733. }
  30734. }
  30735. this.positions = this._mergeElement(this.positions, other.positions);
  30736. if (!this.positions) {
  30737. return this;
  30738. }
  30739. var count = this.positions.length / 3;
  30740. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30741. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30742. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30743. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30744. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30745. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30746. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30747. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30748. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30749. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30750. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30751. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30752. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30753. return this;
  30754. };
  30755. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30756. if (length === void 0) { length = 0; }
  30757. if (defaultValue === void 0) { defaultValue = 0; }
  30758. if (!other && !source) {
  30759. return null;
  30760. }
  30761. if (!other) {
  30762. var padding = new Float32Array(source.length);
  30763. padding.fill(defaultValue);
  30764. return this._mergeElement(source, padding, length);
  30765. }
  30766. if (!source) {
  30767. if (length === 0 || length === other.length) {
  30768. return other;
  30769. }
  30770. var padding = new Float32Array(length - other.length);
  30771. padding.fill(defaultValue);
  30772. return this._mergeElement(padding, other, length);
  30773. }
  30774. var len = other.length + source.length;
  30775. var isSrcTypedArray = source instanceof Float32Array;
  30776. var isOthTypedArray = other instanceof Float32Array;
  30777. // use non-loop method when the source is Float32Array
  30778. if (isSrcTypedArray) {
  30779. var ret32 = new Float32Array(len);
  30780. ret32.set(source);
  30781. ret32.set(other, source.length);
  30782. return ret32;
  30783. // source is number[], when other is also use concat
  30784. }
  30785. else if (!isOthTypedArray) {
  30786. return source.concat(other);
  30787. // source is a number[], but other is a Float32Array, loop required
  30788. }
  30789. else {
  30790. var ret = source.slice(0); // copy source to a separate array
  30791. for (var i = 0, len = other.length; i < len; i++) {
  30792. ret.push(other[i]);
  30793. }
  30794. return ret;
  30795. }
  30796. };
  30797. /**
  30798. * Serializes the VertexData.
  30799. * Returns a serialized object.
  30800. */
  30801. VertexData.prototype.serialize = function () {
  30802. var serializationObject = this.serialize();
  30803. if (this.positions) {
  30804. serializationObject.positions = this.positions;
  30805. }
  30806. if (this.normals) {
  30807. serializationObject.normals = this.normals;
  30808. }
  30809. if (this.tangents) {
  30810. serializationObject.tangents = this.tangents;
  30811. }
  30812. if (this.uvs) {
  30813. serializationObject.uvs = this.uvs;
  30814. }
  30815. if (this.uvs2) {
  30816. serializationObject.uvs2 = this.uvs2;
  30817. }
  30818. if (this.uvs3) {
  30819. serializationObject.uvs3 = this.uvs3;
  30820. }
  30821. if (this.uvs4) {
  30822. serializationObject.uvs4 = this.uvs4;
  30823. }
  30824. if (this.uvs5) {
  30825. serializationObject.uvs5 = this.uvs5;
  30826. }
  30827. if (this.uvs6) {
  30828. serializationObject.uvs6 = this.uvs6;
  30829. }
  30830. if (this.colors) {
  30831. serializationObject.colors = this.colors;
  30832. }
  30833. if (this.matricesIndices) {
  30834. serializationObject.matricesIndices = this.matricesIndices;
  30835. serializationObject.matricesIndices._isExpanded = true;
  30836. }
  30837. if (this.matricesWeights) {
  30838. serializationObject.matricesWeights = this.matricesWeights;
  30839. }
  30840. if (this.matricesIndicesExtra) {
  30841. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30842. serializationObject.matricesIndicesExtra._isExpanded = true;
  30843. }
  30844. if (this.matricesWeightsExtra) {
  30845. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30846. }
  30847. serializationObject.indices = this.indices;
  30848. return serializationObject;
  30849. };
  30850. // Statics
  30851. /**
  30852. * Returns the object VertexData associated to the passed mesh.
  30853. */
  30854. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30855. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30856. };
  30857. /**
  30858. * Returns the object VertexData associated to the passed geometry.
  30859. */
  30860. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30861. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30862. };
  30863. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30864. var result = new VertexData();
  30865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30866. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30867. }
  30868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30869. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30870. }
  30871. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30872. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30873. }
  30874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30875. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30876. }
  30877. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30878. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30879. }
  30880. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30881. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30882. }
  30883. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30884. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30885. }
  30886. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30887. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30888. }
  30889. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30890. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30891. }
  30892. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30893. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30894. }
  30895. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30896. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30897. }
  30898. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30899. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30900. }
  30901. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30902. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30903. }
  30904. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30905. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30906. }
  30907. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30908. return result;
  30909. };
  30910. /**
  30911. * Creates the vertexData of the Ribbon.
  30912. */
  30913. VertexData.CreateRibbon = function (options) {
  30914. var pathArray = options.pathArray;
  30915. var closeArray = options.closeArray || false;
  30916. var closePath = options.closePath || false;
  30917. var invertUV = options.invertUV || false;
  30918. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30919. var offset = options.offset || defaultOffset;
  30920. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30921. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30922. var customUV = options.uvs;
  30923. var customColors = options.colors;
  30924. var positions = [];
  30925. var indices = [];
  30926. var normals = [];
  30927. var uvs = [];
  30928. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30929. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30930. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30931. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30932. var minlg; // minimal length among all paths from pathArray
  30933. var lg = []; // array of path lengths : nb of vertex per path
  30934. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30935. var p; // path iterator
  30936. var i; // point iterator
  30937. var j; // point iterator
  30938. // if single path in pathArray
  30939. if (pathArray.length < 2) {
  30940. var ar1 = [];
  30941. var ar2 = [];
  30942. for (i = 0; i < pathArray[0].length - offset; i++) {
  30943. ar1.push(pathArray[0][i]);
  30944. ar2.push(pathArray[0][i + offset]);
  30945. }
  30946. pathArray = [ar1, ar2];
  30947. }
  30948. // positions and horizontal distances (u)
  30949. var idc = 0;
  30950. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30951. var path;
  30952. var l;
  30953. minlg = pathArray[0].length;
  30954. var vectlg;
  30955. var dist;
  30956. for (p = 0; p < pathArray.length; p++) {
  30957. uTotalDistance[p] = 0;
  30958. us[p] = [0];
  30959. path = pathArray[p];
  30960. l = path.length;
  30961. minlg = (minlg < l) ? minlg : l;
  30962. j = 0;
  30963. while (j < l) {
  30964. positions.push(path[j].x, path[j].y, path[j].z);
  30965. if (j > 0) {
  30966. vectlg = path[j].subtract(path[j - 1]).length();
  30967. dist = vectlg + uTotalDistance[p];
  30968. us[p].push(dist);
  30969. uTotalDistance[p] = dist;
  30970. }
  30971. j++;
  30972. }
  30973. if (closePath) {
  30974. j--;
  30975. positions.push(path[0].x, path[0].y, path[0].z);
  30976. vectlg = path[j].subtract(path[0]).length();
  30977. dist = vectlg + uTotalDistance[p];
  30978. us[p].push(dist);
  30979. uTotalDistance[p] = dist;
  30980. }
  30981. lg[p] = l + closePathCorr;
  30982. idx[p] = idc;
  30983. idc += (l + closePathCorr);
  30984. }
  30985. // vertical distances (v)
  30986. var path1;
  30987. var path2;
  30988. var vertex1 = null;
  30989. var vertex2 = null;
  30990. for (i = 0; i < minlg + closePathCorr; i++) {
  30991. vTotalDistance[i] = 0;
  30992. vs[i] = [0];
  30993. for (p = 0; p < pathArray.length - 1; p++) {
  30994. path1 = pathArray[p];
  30995. path2 = pathArray[p + 1];
  30996. if (i === minlg) {
  30997. vertex1 = path1[0];
  30998. vertex2 = path2[0];
  30999. }
  31000. else {
  31001. vertex1 = path1[i];
  31002. vertex2 = path2[i];
  31003. }
  31004. vectlg = vertex2.subtract(vertex1).length();
  31005. dist = vectlg + vTotalDistance[i];
  31006. vs[i].push(dist);
  31007. vTotalDistance[i] = dist;
  31008. }
  31009. if (closeArray && vertex2 && vertex1) {
  31010. path1 = pathArray[p];
  31011. path2 = pathArray[0];
  31012. if (i === minlg) {
  31013. vertex2 = path2[0];
  31014. }
  31015. vectlg = vertex2.subtract(vertex1).length();
  31016. dist = vectlg + vTotalDistance[i];
  31017. vTotalDistance[i] = dist;
  31018. }
  31019. }
  31020. // uvs
  31021. var u;
  31022. var v;
  31023. if (customUV) {
  31024. for (p = 0; p < customUV.length; p++) {
  31025. uvs.push(customUV[p].x, customUV[p].y);
  31026. }
  31027. }
  31028. else {
  31029. for (p = 0; p < pathArray.length; p++) {
  31030. for (i = 0; i < minlg + closePathCorr; i++) {
  31031. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  31032. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  31033. if (invertUV) {
  31034. uvs.push(v, u);
  31035. }
  31036. else {
  31037. uvs.push(u, v);
  31038. }
  31039. }
  31040. }
  31041. }
  31042. // indices
  31043. p = 0; // path index
  31044. var pi = 0; // positions array index
  31045. var l1 = lg[p] - 1; // path1 length
  31046. var l2 = lg[p + 1] - 1; // path2 length
  31047. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31048. var shft = idx[1] - idx[0]; // shift
  31049. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31050. while (pi <= min && p < path1nb) {
  31051. // 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
  31052. indices.push(pi, pi + shft, pi + 1);
  31053. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31054. pi += 1;
  31055. if (pi === min) {
  31056. p++;
  31057. if (p === lg.length - 1) {
  31058. shft = idx[0] - idx[p];
  31059. l1 = lg[p] - 1;
  31060. l2 = lg[0] - 1;
  31061. }
  31062. else {
  31063. shft = idx[p + 1] - idx[p];
  31064. l1 = lg[p] - 1;
  31065. l2 = lg[p + 1] - 1;
  31066. }
  31067. pi = idx[p];
  31068. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31069. }
  31070. }
  31071. // normals
  31072. VertexData.ComputeNormals(positions, indices, normals);
  31073. if (closePath) {
  31074. var indexFirst = 0;
  31075. var indexLast = 0;
  31076. for (p = 0; p < pathArray.length; p++) {
  31077. indexFirst = idx[p] * 3;
  31078. if (p + 1 < pathArray.length) {
  31079. indexLast = (idx[p + 1] - 1) * 3;
  31080. }
  31081. else {
  31082. indexLast = normals.length - 3;
  31083. }
  31084. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31085. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31086. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31087. normals[indexLast] = normals[indexFirst];
  31088. normals[indexLast + 1] = normals[indexFirst + 1];
  31089. normals[indexLast + 2] = normals[indexFirst + 2];
  31090. }
  31091. }
  31092. // sides
  31093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31094. // Colors
  31095. var colors = null;
  31096. if (customColors) {
  31097. colors = new Float32Array(customColors.length * 4);
  31098. for (var c = 0; c < customColors.length; c++) {
  31099. colors[c * 4] = customColors[c].r;
  31100. colors[c * 4 + 1] = customColors[c].g;
  31101. colors[c * 4 + 2] = customColors[c].b;
  31102. colors[c * 4 + 3] = customColors[c].a;
  31103. }
  31104. }
  31105. // Result
  31106. var vertexData = new VertexData();
  31107. var positions32 = new Float32Array(positions);
  31108. var normals32 = new Float32Array(normals);
  31109. var uvs32 = new Float32Array(uvs);
  31110. vertexData.indices = indices;
  31111. vertexData.positions = positions32;
  31112. vertexData.normals = normals32;
  31113. vertexData.uvs = uvs32;
  31114. if (colors) {
  31115. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  31116. }
  31117. if (closePath) {
  31118. vertexData._idx = idx;
  31119. }
  31120. return vertexData;
  31121. };
  31122. /**
  31123. * Creates the VertexData of the Box.
  31124. */
  31125. VertexData.CreateBox = function (options) {
  31126. var normalsSource = [
  31127. new BABYLON.Vector3(0, 0, 1),
  31128. new BABYLON.Vector3(0, 0, -1),
  31129. new BABYLON.Vector3(1, 0, 0),
  31130. new BABYLON.Vector3(-1, 0, 0),
  31131. new BABYLON.Vector3(0, 1, 0),
  31132. new BABYLON.Vector3(0, -1, 0)
  31133. ];
  31134. var indices = [];
  31135. var positions = [];
  31136. var normals = [];
  31137. var uvs = [];
  31138. var width = options.width || options.size || 1;
  31139. var height = options.height || options.size || 1;
  31140. var depth = options.depth || options.size || 1;
  31141. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31142. var faceUV = options.faceUV || new Array(6);
  31143. var faceColors = options.faceColors;
  31144. var colors = [];
  31145. // default face colors and UV if undefined
  31146. for (var f = 0; f < 6; f++) {
  31147. if (faceUV[f] === undefined) {
  31148. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31149. }
  31150. if (faceColors && faceColors[f] === undefined) {
  31151. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31152. }
  31153. }
  31154. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31155. // Create each face in turn.
  31156. for (var index = 0; index < normalsSource.length; index++) {
  31157. var normal = normalsSource[index];
  31158. // Get two vectors perpendicular to the face normal and to each other.
  31159. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31160. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31161. // Six indices (two triangles) per face.
  31162. var verticesLength = positions.length / 3;
  31163. indices.push(verticesLength);
  31164. indices.push(verticesLength + 1);
  31165. indices.push(verticesLength + 2);
  31166. indices.push(verticesLength);
  31167. indices.push(verticesLength + 2);
  31168. indices.push(verticesLength + 3);
  31169. // Four vertices per face.
  31170. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31171. positions.push(vertex.x, vertex.y, vertex.z);
  31172. normals.push(normal.x, normal.y, normal.z);
  31173. uvs.push(faceUV[index].z, faceUV[index].w);
  31174. if (faceColors) {
  31175. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31176. }
  31177. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31178. positions.push(vertex.x, vertex.y, vertex.z);
  31179. normals.push(normal.x, normal.y, normal.z);
  31180. uvs.push(faceUV[index].x, faceUV[index].w);
  31181. if (faceColors) {
  31182. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31183. }
  31184. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31185. positions.push(vertex.x, vertex.y, vertex.z);
  31186. normals.push(normal.x, normal.y, normal.z);
  31187. uvs.push(faceUV[index].x, faceUV[index].y);
  31188. if (faceColors) {
  31189. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31190. }
  31191. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31192. positions.push(vertex.x, vertex.y, vertex.z);
  31193. normals.push(normal.x, normal.y, normal.z);
  31194. uvs.push(faceUV[index].z, faceUV[index].y);
  31195. if (faceColors) {
  31196. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31197. }
  31198. }
  31199. // sides
  31200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31201. // Result
  31202. var vertexData = new VertexData();
  31203. vertexData.indices = indices;
  31204. vertexData.positions = positions;
  31205. vertexData.normals = normals;
  31206. vertexData.uvs = uvs;
  31207. if (faceColors) {
  31208. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31209. vertexData.colors = totalColors;
  31210. }
  31211. return vertexData;
  31212. };
  31213. /**
  31214. * Creates the VertexData of the Sphere.
  31215. */
  31216. VertexData.CreateSphere = function (options) {
  31217. var segments = options.segments || 32;
  31218. var diameterX = options.diameterX || options.diameter || 1;
  31219. var diameterY = options.diameterY || options.diameter || 1;
  31220. var diameterZ = options.diameterZ || options.diameter || 1;
  31221. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31222. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31223. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31224. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31225. var totalZRotationSteps = 2 + segments;
  31226. var totalYRotationSteps = 2 * totalZRotationSteps;
  31227. var indices = [];
  31228. var positions = [];
  31229. var normals = [];
  31230. var uvs = [];
  31231. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31232. var normalizedZ = zRotationStep / totalZRotationSteps;
  31233. var angleZ = normalizedZ * Math.PI * slice;
  31234. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31235. var normalizedY = yRotationStep / totalYRotationSteps;
  31236. var angleY = normalizedY * Math.PI * 2 * arc;
  31237. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31238. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31239. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31240. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31241. var vertex = complete.multiply(radius);
  31242. var normal = complete.divide(radius).normalize();
  31243. positions.push(vertex.x, vertex.y, vertex.z);
  31244. normals.push(normal.x, normal.y, normal.z);
  31245. uvs.push(normalizedY, normalizedZ);
  31246. }
  31247. if (zRotationStep > 0) {
  31248. var verticesCount = positions.length / 3;
  31249. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31250. indices.push((firstIndex));
  31251. indices.push((firstIndex + 1));
  31252. indices.push(firstIndex + totalYRotationSteps + 1);
  31253. indices.push((firstIndex + totalYRotationSteps + 1));
  31254. indices.push((firstIndex + 1));
  31255. indices.push((firstIndex + totalYRotationSteps + 2));
  31256. }
  31257. }
  31258. }
  31259. // Sides
  31260. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31261. // Result
  31262. var vertexData = new VertexData();
  31263. vertexData.indices = indices;
  31264. vertexData.positions = positions;
  31265. vertexData.normals = normals;
  31266. vertexData.uvs = uvs;
  31267. return vertexData;
  31268. };
  31269. /**
  31270. * Creates the VertexData of the Cylinder or Cone.
  31271. */
  31272. VertexData.CreateCylinder = function (options) {
  31273. var height = options.height || 2;
  31274. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31275. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31276. var tessellation = options.tessellation || 24;
  31277. var subdivisions = options.subdivisions || 1;
  31278. var hasRings = options.hasRings ? true : false;
  31279. var enclose = options.enclose ? true : false;
  31280. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31281. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31282. var faceUV = options.faceUV || new Array(3);
  31283. var faceColors = options.faceColors;
  31284. // default face colors and UV if undefined
  31285. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31286. var ringNb = (hasRings) ? subdivisions : 1;
  31287. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31288. var f;
  31289. for (f = 0; f < surfaceNb; f++) {
  31290. if (faceColors && faceColors[f] === undefined) {
  31291. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31292. }
  31293. }
  31294. for (f = 0; f < surfaceNb; f++) {
  31295. if (faceUV && faceUV[f] === undefined) {
  31296. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31297. }
  31298. }
  31299. var indices = new Array();
  31300. var positions = new Array();
  31301. var normals = new Array();
  31302. var uvs = new Array();
  31303. var colors = new Array();
  31304. var angle_step = Math.PI * 2 * arc / tessellation;
  31305. var angle;
  31306. var h;
  31307. var radius;
  31308. var tan = (diameterBottom - diameterTop) / 2 / height;
  31309. var ringVertex = BABYLON.Vector3.Zero();
  31310. var ringNormal = BABYLON.Vector3.Zero();
  31311. var ringFirstVertex = BABYLON.Vector3.Zero();
  31312. var ringFirstNormal = BABYLON.Vector3.Zero();
  31313. var quadNormal = BABYLON.Vector3.Zero();
  31314. var Y = BABYLON.Axis.Y;
  31315. // positions, normals, uvs
  31316. var i;
  31317. var j;
  31318. var r;
  31319. var ringIdx = 1;
  31320. var s = 1; // surface index
  31321. var cs = 0;
  31322. var v = 0;
  31323. for (i = 0; i <= subdivisions; i++) {
  31324. h = i / subdivisions;
  31325. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31326. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31327. for (r = 0; r < ringIdx; r++) {
  31328. if (hasRings) {
  31329. s += r;
  31330. }
  31331. if (enclose) {
  31332. s += 2 * r;
  31333. }
  31334. for (j = 0; j <= tessellation; j++) {
  31335. angle = j * angle_step;
  31336. // position
  31337. ringVertex.x = Math.cos(-angle) * radius;
  31338. ringVertex.y = -height / 2 + h * height;
  31339. ringVertex.z = Math.sin(-angle) * radius;
  31340. // normal
  31341. if (diameterTop === 0 && i === subdivisions) {
  31342. // if no top cap, reuse former normals
  31343. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31344. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31345. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31346. }
  31347. else {
  31348. ringNormal.x = ringVertex.x;
  31349. ringNormal.z = ringVertex.z;
  31350. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31351. ringNormal.normalize();
  31352. }
  31353. // keep first ring vertex values for enclose
  31354. if (j === 0) {
  31355. ringFirstVertex.copyFrom(ringVertex);
  31356. ringFirstNormal.copyFrom(ringNormal);
  31357. }
  31358. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31359. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31360. if (hasRings) {
  31361. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31362. }
  31363. else {
  31364. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31365. }
  31366. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31367. if (faceColors) {
  31368. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31369. }
  31370. }
  31371. // if enclose, add four vertices and their dedicated normals
  31372. if (arc !== 1 && enclose) {
  31373. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31374. positions.push(0, ringVertex.y, 0);
  31375. positions.push(0, ringVertex.y, 0);
  31376. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31377. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31378. quadNormal.normalize();
  31379. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31380. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31381. quadNormal.normalize();
  31382. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31383. if (hasRings) {
  31384. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31385. }
  31386. else {
  31387. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31388. }
  31389. uvs.push(faceUV[s + 1].x, v);
  31390. uvs.push(faceUV[s + 1].z, v);
  31391. if (hasRings) {
  31392. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31393. }
  31394. else {
  31395. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31396. }
  31397. uvs.push(faceUV[s + 2].x, v);
  31398. uvs.push(faceUV[s + 2].z, v);
  31399. if (faceColors) {
  31400. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31401. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31402. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31403. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31404. }
  31405. }
  31406. if (cs !== s) {
  31407. cs = s;
  31408. }
  31409. }
  31410. }
  31411. // indices
  31412. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31413. var s;
  31414. i = 0;
  31415. for (s = 0; s < subdivisions; s++) {
  31416. var i0 = 0;
  31417. var i1 = 0;
  31418. var i2 = 0;
  31419. var i3 = 0;
  31420. for (j = 0; j < tessellation; j++) {
  31421. i0 = i * (e + 1) + j;
  31422. i1 = (i + 1) * (e + 1) + j;
  31423. i2 = i * (e + 1) + (j + 1);
  31424. i3 = (i + 1) * (e + 1) + (j + 1);
  31425. indices.push(i0, i1, i2);
  31426. indices.push(i3, i2, i1);
  31427. }
  31428. if (arc !== 1 && enclose) {
  31429. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31430. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31431. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31432. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31433. }
  31434. i = (hasRings) ? (i + 2) : (i + 1);
  31435. }
  31436. // Caps
  31437. var createCylinderCap = function (isTop) {
  31438. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31439. if (radius === 0) {
  31440. return;
  31441. }
  31442. // Cap positions, normals & uvs
  31443. var angle;
  31444. var circleVector;
  31445. var i;
  31446. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31447. var c = null;
  31448. if (faceColors) {
  31449. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31450. }
  31451. // cap center
  31452. var vbase = positions.length / 3;
  31453. var offset = isTop ? height / 2 : -height / 2;
  31454. var center = new BABYLON.Vector3(0, offset, 0);
  31455. positions.push(center.x, center.y, center.z);
  31456. normals.push(0, isTop ? 1 : -1, 0);
  31457. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31458. if (c) {
  31459. colors.push(c.r, c.g, c.b, c.a);
  31460. }
  31461. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31462. for (i = 0; i <= tessellation; i++) {
  31463. angle = Math.PI * 2 * i * arc / tessellation;
  31464. var cos = Math.cos(-angle);
  31465. var sin = Math.sin(-angle);
  31466. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31467. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31468. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31469. normals.push(0, isTop ? 1 : -1, 0);
  31470. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31471. if (c) {
  31472. colors.push(c.r, c.g, c.b, c.a);
  31473. }
  31474. }
  31475. // Cap indices
  31476. for (i = 0; i < tessellation; i++) {
  31477. if (!isTop) {
  31478. indices.push(vbase);
  31479. indices.push(vbase + (i + 1));
  31480. indices.push(vbase + (i + 2));
  31481. }
  31482. else {
  31483. indices.push(vbase);
  31484. indices.push(vbase + (i + 2));
  31485. indices.push(vbase + (i + 1));
  31486. }
  31487. }
  31488. };
  31489. // add caps to geometry
  31490. createCylinderCap(false);
  31491. createCylinderCap(true);
  31492. // Sides
  31493. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31494. var vertexData = new VertexData();
  31495. vertexData.indices = indices;
  31496. vertexData.positions = positions;
  31497. vertexData.normals = normals;
  31498. vertexData.uvs = uvs;
  31499. if (faceColors) {
  31500. vertexData.colors = colors;
  31501. }
  31502. return vertexData;
  31503. };
  31504. /**
  31505. * Creates the VertexData of the Torus.
  31506. */
  31507. VertexData.CreateTorus = function (options) {
  31508. var indices = [];
  31509. var positions = [];
  31510. var normals = [];
  31511. var uvs = [];
  31512. var diameter = options.diameter || 1;
  31513. var thickness = options.thickness || 0.5;
  31514. var tessellation = options.tessellation || 16;
  31515. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31516. var stride = tessellation + 1;
  31517. for (var i = 0; i <= tessellation; i++) {
  31518. var u = i / tessellation;
  31519. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31520. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31521. for (var j = 0; j <= tessellation; j++) {
  31522. var v = 1 - j / tessellation;
  31523. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31524. var dx = Math.cos(innerAngle);
  31525. var dy = Math.sin(innerAngle);
  31526. // Create a vertex.
  31527. var normal = new BABYLON.Vector3(dx, dy, 0);
  31528. var position = normal.scale(thickness / 2);
  31529. var textureCoordinate = new BABYLON.Vector2(u, v);
  31530. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31531. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31532. positions.push(position.x, position.y, position.z);
  31533. normals.push(normal.x, normal.y, normal.z);
  31534. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31535. // And create indices for two triangles.
  31536. var nextI = (i + 1) % stride;
  31537. var nextJ = (j + 1) % stride;
  31538. indices.push(i * stride + j);
  31539. indices.push(i * stride + nextJ);
  31540. indices.push(nextI * stride + j);
  31541. indices.push(i * stride + nextJ);
  31542. indices.push(nextI * stride + nextJ);
  31543. indices.push(nextI * stride + j);
  31544. }
  31545. }
  31546. // Sides
  31547. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31548. // Result
  31549. var vertexData = new VertexData();
  31550. vertexData.indices = indices;
  31551. vertexData.positions = positions;
  31552. vertexData.normals = normals;
  31553. vertexData.uvs = uvs;
  31554. return vertexData;
  31555. };
  31556. /**
  31557. * Creates the VertexData of the LineSystem.
  31558. */
  31559. VertexData.CreateLineSystem = function (options) {
  31560. var indices = [];
  31561. var positions = [];
  31562. var lines = options.lines;
  31563. var colors = options.colors;
  31564. var vertexColors = [];
  31565. var idx = 0;
  31566. for (var l = 0; l < lines.length; l++) {
  31567. var points = lines[l];
  31568. for (var index = 0; index < points.length; index++) {
  31569. positions.push(points[index].x, points[index].y, points[index].z);
  31570. if (colors) {
  31571. var color = colors[l];
  31572. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31573. }
  31574. if (index > 0) {
  31575. indices.push(idx - 1);
  31576. indices.push(idx);
  31577. }
  31578. idx++;
  31579. }
  31580. }
  31581. var vertexData = new VertexData();
  31582. vertexData.indices = indices;
  31583. vertexData.positions = positions;
  31584. if (colors) {
  31585. vertexData.colors = vertexColors;
  31586. }
  31587. return vertexData;
  31588. };
  31589. /**
  31590. * Create the VertexData of the DashedLines.
  31591. */
  31592. VertexData.CreateDashedLines = function (options) {
  31593. var dashSize = options.dashSize || 3;
  31594. var gapSize = options.gapSize || 1;
  31595. var dashNb = options.dashNb || 200;
  31596. var points = options.points;
  31597. var positions = new Array();
  31598. var indices = new Array();
  31599. var curvect = BABYLON.Vector3.Zero();
  31600. var lg = 0;
  31601. var nb = 0;
  31602. var shft = 0;
  31603. var dashshft = 0;
  31604. var curshft = 0;
  31605. var idx = 0;
  31606. var i = 0;
  31607. for (i = 0; i < points.length - 1; i++) {
  31608. points[i + 1].subtractToRef(points[i], curvect);
  31609. lg += curvect.length();
  31610. }
  31611. shft = lg / dashNb;
  31612. dashshft = dashSize * shft / (dashSize + gapSize);
  31613. for (i = 0; i < points.length - 1; i++) {
  31614. points[i + 1].subtractToRef(points[i], curvect);
  31615. nb = Math.floor(curvect.length() / shft);
  31616. curvect.normalize();
  31617. for (var j = 0; j < nb; j++) {
  31618. curshft = shft * j;
  31619. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31620. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31621. indices.push(idx, idx + 1);
  31622. idx += 2;
  31623. }
  31624. }
  31625. // Result
  31626. var vertexData = new VertexData();
  31627. vertexData.positions = positions;
  31628. vertexData.indices = indices;
  31629. return vertexData;
  31630. };
  31631. /**
  31632. * Creates the VertexData of the Ground.
  31633. */
  31634. VertexData.CreateGround = function (options) {
  31635. var indices = [];
  31636. var positions = [];
  31637. var normals = [];
  31638. var uvs = [];
  31639. var row, col;
  31640. var width = options.width || 1;
  31641. var height = options.height || 1;
  31642. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31643. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31644. for (row = 0; row <= subdivisionsY; row++) {
  31645. for (col = 0; col <= subdivisionsX; col++) {
  31646. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31647. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31648. positions.push(position.x, position.y, position.z);
  31649. normals.push(normal.x, normal.y, normal.z);
  31650. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31651. }
  31652. }
  31653. for (row = 0; row < subdivisionsY; row++) {
  31654. for (col = 0; col < subdivisionsX; col++) {
  31655. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31656. indices.push(col + 1 + row * (subdivisionsX + 1));
  31657. indices.push(col + row * (subdivisionsX + 1));
  31658. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31659. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31660. indices.push(col + row * (subdivisionsX + 1));
  31661. }
  31662. }
  31663. // Result
  31664. var vertexData = new VertexData();
  31665. vertexData.indices = indices;
  31666. vertexData.positions = positions;
  31667. vertexData.normals = normals;
  31668. vertexData.uvs = uvs;
  31669. return vertexData;
  31670. };
  31671. /**
  31672. * Creates the VertexData of the TiledGround.
  31673. */
  31674. VertexData.CreateTiledGround = function (options) {
  31675. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31676. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31677. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31678. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31679. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31680. var precision = options.precision || { w: 1, h: 1 };
  31681. var indices = new Array();
  31682. var positions = new Array();
  31683. var normals = new Array();
  31684. var uvs = new Array();
  31685. var row, col, tileRow, tileCol;
  31686. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31687. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31688. precision.w = (precision.w < 1) ? 1 : precision.w;
  31689. precision.h = (precision.h < 1) ? 1 : precision.h;
  31690. var tileSize = {
  31691. 'w': (xmax - xmin) / subdivisions.w,
  31692. 'h': (zmax - zmin) / subdivisions.h
  31693. };
  31694. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31695. // Indices
  31696. var base = positions.length / 3;
  31697. var rowLength = precision.w + 1;
  31698. for (row = 0; row < precision.h; row++) {
  31699. for (col = 0; col < precision.w; col++) {
  31700. var square = [
  31701. base + col + row * rowLength,
  31702. base + (col + 1) + row * rowLength,
  31703. base + (col + 1) + (row + 1) * rowLength,
  31704. base + col + (row + 1) * rowLength
  31705. ];
  31706. indices.push(square[1]);
  31707. indices.push(square[2]);
  31708. indices.push(square[3]);
  31709. indices.push(square[0]);
  31710. indices.push(square[1]);
  31711. indices.push(square[3]);
  31712. }
  31713. }
  31714. // Position, normals and uvs
  31715. var position = BABYLON.Vector3.Zero();
  31716. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31717. for (row = 0; row <= precision.h; row++) {
  31718. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31719. for (col = 0; col <= precision.w; col++) {
  31720. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31721. position.y = 0;
  31722. positions.push(position.x, position.y, position.z);
  31723. normals.push(normal.x, normal.y, normal.z);
  31724. uvs.push(col / precision.w, row / precision.h);
  31725. }
  31726. }
  31727. }
  31728. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31729. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31730. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31731. }
  31732. }
  31733. // Result
  31734. var vertexData = new VertexData();
  31735. vertexData.indices = indices;
  31736. vertexData.positions = positions;
  31737. vertexData.normals = normals;
  31738. vertexData.uvs = uvs;
  31739. return vertexData;
  31740. };
  31741. /**
  31742. * Creates the VertexData of the Ground designed from a heightmap.
  31743. */
  31744. VertexData.CreateGroundFromHeightMap = function (options) {
  31745. var indices = [];
  31746. var positions = [];
  31747. var normals = [];
  31748. var uvs = [];
  31749. var row, col;
  31750. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31751. // Vertices
  31752. for (row = 0; row <= options.subdivisions; row++) {
  31753. for (col = 0; col <= options.subdivisions; col++) {
  31754. 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));
  31755. // Compute height
  31756. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31757. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31758. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31759. var r = options.buffer[pos] / 255.0;
  31760. var g = options.buffer[pos + 1] / 255.0;
  31761. var b = options.buffer[pos + 2] / 255.0;
  31762. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31763. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31764. // Add vertex
  31765. positions.push(position.x, position.y, position.z);
  31766. normals.push(0, 0, 0);
  31767. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31768. }
  31769. }
  31770. // Indices
  31771. for (row = 0; row < options.subdivisions; row++) {
  31772. for (col = 0; col < options.subdivisions; col++) {
  31773. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31774. indices.push(col + 1 + row * (options.subdivisions + 1));
  31775. indices.push(col + row * (options.subdivisions + 1));
  31776. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31777. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31778. indices.push(col + row * (options.subdivisions + 1));
  31779. }
  31780. }
  31781. // Normals
  31782. VertexData.ComputeNormals(positions, indices, normals);
  31783. // Result
  31784. var vertexData = new VertexData();
  31785. vertexData.indices = indices;
  31786. vertexData.positions = positions;
  31787. vertexData.normals = normals;
  31788. vertexData.uvs = uvs;
  31789. return vertexData;
  31790. };
  31791. /**
  31792. * Creates the VertexData of the Plane.
  31793. */
  31794. VertexData.CreatePlane = function (options) {
  31795. var indices = [];
  31796. var positions = [];
  31797. var normals = [];
  31798. var uvs = [];
  31799. var width = options.width || options.size || 1;
  31800. var height = options.height || options.size || 1;
  31801. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31802. // Vertices
  31803. var halfWidth = width / 2.0;
  31804. var halfHeight = height / 2.0;
  31805. positions.push(-halfWidth, -halfHeight, 0);
  31806. normals.push(0, 0, -1.0);
  31807. uvs.push(0.0, 0.0);
  31808. positions.push(halfWidth, -halfHeight, 0);
  31809. normals.push(0, 0, -1.0);
  31810. uvs.push(1.0, 0.0);
  31811. positions.push(halfWidth, halfHeight, 0);
  31812. normals.push(0, 0, -1.0);
  31813. uvs.push(1.0, 1.0);
  31814. positions.push(-halfWidth, halfHeight, 0);
  31815. normals.push(0, 0, -1.0);
  31816. uvs.push(0.0, 1.0);
  31817. // Indices
  31818. indices.push(0);
  31819. indices.push(1);
  31820. indices.push(2);
  31821. indices.push(0);
  31822. indices.push(2);
  31823. indices.push(3);
  31824. // Sides
  31825. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31826. // Result
  31827. var vertexData = new VertexData();
  31828. vertexData.indices = indices;
  31829. vertexData.positions = positions;
  31830. vertexData.normals = normals;
  31831. vertexData.uvs = uvs;
  31832. return vertexData;
  31833. };
  31834. /**
  31835. * Creates the VertexData of the Disc or regular Polygon.
  31836. */
  31837. VertexData.CreateDisc = function (options) {
  31838. var positions = new Array();
  31839. var indices = new Array();
  31840. var normals = new Array();
  31841. var uvs = new Array();
  31842. var radius = options.radius || 0.5;
  31843. var tessellation = options.tessellation || 64;
  31844. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31845. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31846. // positions and uvs
  31847. positions.push(0, 0, 0); // disc center first
  31848. uvs.push(0.5, 0.5);
  31849. var theta = Math.PI * 2 * arc;
  31850. var step = theta / tessellation;
  31851. for (var a = 0; a < theta; a += step) {
  31852. var x = Math.cos(a);
  31853. var y = Math.sin(a);
  31854. var u = (x + 1) / 2;
  31855. var v = (1 - y) / 2;
  31856. positions.push(radius * x, radius * y, 0);
  31857. uvs.push(u, v);
  31858. }
  31859. if (arc === 1) {
  31860. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31861. uvs.push(uvs[2], uvs[3]);
  31862. }
  31863. //indices
  31864. var vertexNb = positions.length / 3;
  31865. for (var i = 1; i < vertexNb - 1; i++) {
  31866. indices.push(i + 1, 0, i);
  31867. }
  31868. // result
  31869. VertexData.ComputeNormals(positions, indices, normals);
  31870. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31871. var vertexData = new VertexData();
  31872. vertexData.indices = indices;
  31873. vertexData.positions = positions;
  31874. vertexData.normals = normals;
  31875. vertexData.uvs = uvs;
  31876. return vertexData;
  31877. };
  31878. /**
  31879. * Re-creates the VertexData of the Polygon for sideOrientation.
  31880. */
  31881. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31882. var faceUV = fUV || new Array(3);
  31883. var faceColors = fColors;
  31884. var colors = [];
  31885. // default face colors and UV if undefined
  31886. for (var f = 0; f < 3; f++) {
  31887. if (faceUV[f] === undefined) {
  31888. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31889. }
  31890. if (faceColors && faceColors[f] === undefined) {
  31891. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31892. }
  31893. }
  31894. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31895. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31896. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31897. var indices = polygon.getIndices();
  31898. // set face colours and textures
  31899. var idx = 0;
  31900. var face = 0;
  31901. for (var index = 0; index < normals.length; index += 3) {
  31902. //Edge Face no. 1
  31903. if (Math.abs(normals[index + 1]) < 0.001) {
  31904. face = 1;
  31905. }
  31906. //Top Face no. 0
  31907. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31908. face = 0;
  31909. }
  31910. //Bottom Face no. 2
  31911. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31912. face = 2;
  31913. }
  31914. idx = index / 3;
  31915. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31916. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31917. if (faceColors) {
  31918. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31919. }
  31920. }
  31921. // sides
  31922. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31923. // Result
  31924. var vertexData = new VertexData();
  31925. vertexData.indices = indices;
  31926. vertexData.positions = positions;
  31927. vertexData.normals = normals;
  31928. vertexData.uvs = uvs;
  31929. if (faceColors) {
  31930. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31931. vertexData.colors = totalColors;
  31932. }
  31933. return vertexData;
  31934. };
  31935. /**
  31936. * Creates the VertexData of the IcoSphere.
  31937. */
  31938. VertexData.CreateIcoSphere = function (options) {
  31939. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31940. var radius = options.radius || 1;
  31941. var flat = (options.flat === undefined) ? true : options.flat;
  31942. var subdivisions = options.subdivisions || 4;
  31943. var radiusX = options.radiusX || radius;
  31944. var radiusY = options.radiusY || radius;
  31945. var radiusZ = options.radiusZ || radius;
  31946. var t = (1 + Math.sqrt(5)) / 2;
  31947. // 12 vertex x,y,z
  31948. var ico_vertices = [
  31949. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31950. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31951. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31952. ];
  31953. // index of 3 vertex makes a face of icopshere
  31954. var ico_indices = [
  31955. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31956. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31957. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31958. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31959. ];
  31960. // vertex for uv have aliased position, not for UV
  31961. var vertices_unalias_id = [
  31962. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31963. // vertex alias
  31964. 0,
  31965. 2,
  31966. 3,
  31967. 3,
  31968. 3,
  31969. 4,
  31970. 7,
  31971. 8,
  31972. 9,
  31973. 9,
  31974. 10,
  31975. 11 // 23: B + 12
  31976. ];
  31977. // uv as integer step (not pixels !)
  31978. var ico_vertexuv = [
  31979. 5, 1, 3, 1, 6, 4, 0, 0,
  31980. 5, 3, 4, 2, 2, 2, 4, 0,
  31981. 2, 0, 1, 1, 6, 0, 6, 2,
  31982. // vertex alias (for same vertex on different faces)
  31983. 0, 4,
  31984. 3, 3,
  31985. 4, 4,
  31986. 3, 1,
  31987. 4, 2,
  31988. 4, 4,
  31989. 0, 2,
  31990. 1, 1,
  31991. 2, 2,
  31992. 3, 3,
  31993. 1, 3,
  31994. 2, 4 // 23: B + 12
  31995. ];
  31996. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31997. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31998. // First island of uv mapping
  31999. // v = 4h 3+ 2
  32000. // v = 3h 9+ 4
  32001. // v = 2h 9+ 5 B
  32002. // v = 1h 9 1 0
  32003. // v = 0h 3 8 7 A
  32004. // u = 0 1 2 3 4 5 6 *a
  32005. // Second island of uv mapping
  32006. // v = 4h 0+ B+ 4+
  32007. // v = 3h A+ 2+
  32008. // v = 2h 7+ 6 3+
  32009. // v = 1h 8+ 3+
  32010. // v = 0h
  32011. // u = 0 1 2 3 4 5 6 *a
  32012. // Face layout on texture UV mapping
  32013. // ============
  32014. // \ 4 /\ 16 / ======
  32015. // \ / \ / /\ 11 /
  32016. // \/ 7 \/ / \ /
  32017. // ======= / 10 \/
  32018. // /\ 17 /\ =======
  32019. // / \ / \ \ 15 /\
  32020. // / 8 \/ 12 \ \ / \
  32021. // ============ \/ 6 \
  32022. // \ 18 /\ ============
  32023. // \ / \ \ 5 /\ 0 /
  32024. // \/ 13 \ \ / \ /
  32025. // ======= \/ 1 \/
  32026. // =============
  32027. // /\ 19 /\ 2 /\
  32028. // / \ / \ / \
  32029. // / 14 \/ 9 \/ 3 \
  32030. // ===================
  32031. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32032. var ustep = 138 / 1024;
  32033. var vstep = 239 / 1024;
  32034. var uoffset = 60 / 1024;
  32035. var voffset = 26 / 1024;
  32036. // Second island should have margin, not to touch the first island
  32037. // avoid any borderline artefact in pixel rounding
  32038. var island_u_offset = -40 / 1024;
  32039. var island_v_offset = +20 / 1024;
  32040. // face is either island 0 or 1 :
  32041. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32042. var island = [
  32043. 0, 0, 0, 0, 1,
  32044. 0, 0, 1, 1, 0,
  32045. 0, 0, 1, 1, 0,
  32046. 0, 1, 1, 1, 0 // 15 - 19
  32047. ];
  32048. var indices = new Array();
  32049. var positions = new Array();
  32050. var normals = new Array();
  32051. var uvs = new Array();
  32052. var current_indice = 0;
  32053. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32054. var face_vertex_pos = new Array(3);
  32055. var face_vertex_uv = new Array(3);
  32056. var v012;
  32057. for (v012 = 0; v012 < 3; v012++) {
  32058. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32059. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32060. }
  32061. // create all with normals
  32062. for (var face = 0; face < 20; face++) {
  32063. // 3 vertex per face
  32064. for (v012 = 0; v012 < 3; v012++) {
  32065. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32066. var v_id = ico_indices[3 * face + v012];
  32067. // vertex have 3D position (x,y,z)
  32068. 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]);
  32069. // Normalize to get normal, then scale to radius
  32070. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32071. // uv Coordinates from vertex ID
  32072. 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);
  32073. }
  32074. // Subdivide the face (interpolate pos, norm, uv)
  32075. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32076. // - norm is linear interpolation of vertex corner normal
  32077. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32078. // - uv is linear interpolation
  32079. //
  32080. // Topology is as below for sub-divide by 2
  32081. // vertex shown as v0,v1,v2
  32082. // interp index is i1 to progress in range [v0,v1[
  32083. // interp index is i2 to progress in range [v0,v2[
  32084. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32085. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32086. //
  32087. //
  32088. // i2 v2
  32089. // ^ ^
  32090. // / / \
  32091. // / / \
  32092. // / / \
  32093. // / / (0,1) \
  32094. // / #---------\
  32095. // / / \ (0,0)'/ \
  32096. // / / \ / \
  32097. // / / \ / \
  32098. // / / (0,0) \ / (1,0) \
  32099. // / #---------#---------\
  32100. // v0 v1
  32101. //
  32102. // --------------------> i1
  32103. //
  32104. // interp of (i1,i2):
  32105. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32106. // along i1 : lerp(x0,x1, i1/(S-i2))
  32107. //
  32108. // centroid of triangle is needed to get help normal computation
  32109. // (c1,c2) are used for centroid location
  32110. var interp_vertex = function (i1, i2, c1, c2) {
  32111. // vertex is interpolated from
  32112. // - face_vertex_pos[0..2]
  32113. // - face_vertex_uv[0..2]
  32114. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32115. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32116. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32117. pos_interp.normalize();
  32118. var vertex_normal;
  32119. if (flat) {
  32120. // in flat mode, recalculate normal as face centroid normal
  32121. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32122. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32123. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32124. }
  32125. else {
  32126. // in smooth mode, recalculate normal from each single vertex position
  32127. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32128. }
  32129. // Vertex normal need correction due to X,Y,Z radius scaling
  32130. vertex_normal.x /= radiusX;
  32131. vertex_normal.y /= radiusY;
  32132. vertex_normal.z /= radiusZ;
  32133. vertex_normal.normalize();
  32134. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32135. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32136. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32137. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32138. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32139. uvs.push(uv_interp.x, uv_interp.y);
  32140. // push each vertex has member of a face
  32141. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32142. indices.push(current_indice);
  32143. current_indice++;
  32144. };
  32145. for (var i2 = 0; i2 < subdivisions; i2++) {
  32146. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32147. // face : (i1,i2) for /\ :
  32148. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32149. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32150. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32151. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32152. if (i1 + i2 + 1 < subdivisions) {
  32153. // face : (i1,i2)' for \/ :
  32154. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32155. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32156. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32157. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32158. }
  32159. }
  32160. }
  32161. }
  32162. // Sides
  32163. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32164. // Result
  32165. var vertexData = new VertexData();
  32166. vertexData.indices = indices;
  32167. vertexData.positions = positions;
  32168. vertexData.normals = normals;
  32169. vertexData.uvs = uvs;
  32170. return vertexData;
  32171. };
  32172. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32173. /**
  32174. * Creates the VertexData of the Polyhedron.
  32175. */
  32176. VertexData.CreatePolyhedron = function (options) {
  32177. // provided polyhedron types :
  32178. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32179. // 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)
  32180. var polyhedra = [];
  32181. 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]] };
  32182. 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]] };
  32183. polyhedra[2] = {
  32184. 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]],
  32185. 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]]
  32186. };
  32187. polyhedra[3] = {
  32188. 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]],
  32189. 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]]
  32190. };
  32191. polyhedra[4] = {
  32192. 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]],
  32193. 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]]
  32194. };
  32195. 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]] };
  32196. 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]] };
  32197. 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]] };
  32198. 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]] };
  32199. 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]] };
  32200. 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]] };
  32201. 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]] };
  32202. 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]] };
  32203. 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]] };
  32204. polyhedra[14] = {
  32205. 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]],
  32206. 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]]
  32207. };
  32208. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32209. var size = options.size;
  32210. var sizeX = options.sizeX || size || 1;
  32211. var sizeY = options.sizeY || size || 1;
  32212. var sizeZ = options.sizeZ || size || 1;
  32213. var data = options.custom || polyhedra[type];
  32214. var nbfaces = data.face.length;
  32215. var faceUV = options.faceUV || new Array(nbfaces);
  32216. var faceColors = options.faceColors;
  32217. var flat = (options.flat === undefined) ? true : options.flat;
  32218. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32219. var positions = new Array();
  32220. var indices = new Array();
  32221. var normals = new Array();
  32222. var uvs = new Array();
  32223. var colors = new Array();
  32224. var index = 0;
  32225. var faceIdx = 0; // face cursor in the array "indexes"
  32226. var indexes = new Array();
  32227. var i = 0;
  32228. var f = 0;
  32229. var u, v, ang, x, y, tmp;
  32230. // default face colors and UV if undefined
  32231. if (flat) {
  32232. for (f = 0; f < nbfaces; f++) {
  32233. if (faceColors && faceColors[f] === undefined) {
  32234. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32235. }
  32236. if (faceUV && faceUV[f] === undefined) {
  32237. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32238. }
  32239. }
  32240. }
  32241. if (!flat) {
  32242. for (i = 0; i < data.vertex.length; i++) {
  32243. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32244. uvs.push(0, 0);
  32245. }
  32246. for (f = 0; f < nbfaces; f++) {
  32247. for (i = 0; i < data.face[f].length - 2; i++) {
  32248. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32249. }
  32250. }
  32251. }
  32252. else {
  32253. for (f = 0; f < nbfaces; f++) {
  32254. var fl = data.face[f].length; // number of vertices of the current face
  32255. ang = 2 * Math.PI / fl;
  32256. x = 0.5 * Math.tan(ang / 2);
  32257. y = 0.5;
  32258. // positions, uvs, colors
  32259. for (i = 0; i < fl; i++) {
  32260. // positions
  32261. 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);
  32262. indexes.push(index);
  32263. index++;
  32264. // uvs
  32265. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32266. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32267. uvs.push(u, v);
  32268. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32269. y = x * Math.sin(ang) + y * Math.cos(ang);
  32270. x = tmp;
  32271. // colors
  32272. if (faceColors) {
  32273. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32274. }
  32275. }
  32276. // indices from indexes
  32277. for (i = 0; i < fl - 2; i++) {
  32278. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32279. }
  32280. faceIdx += fl;
  32281. }
  32282. }
  32283. VertexData.ComputeNormals(positions, indices, normals);
  32284. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32285. var vertexData = new VertexData();
  32286. vertexData.positions = positions;
  32287. vertexData.indices = indices;
  32288. vertexData.normals = normals;
  32289. vertexData.uvs = uvs;
  32290. if (faceColors && flat) {
  32291. vertexData.colors = colors;
  32292. }
  32293. return vertexData;
  32294. };
  32295. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32296. /**
  32297. * Creates the VertexData of the Torus Knot.
  32298. */
  32299. VertexData.CreateTorusKnot = function (options) {
  32300. var indices = new Array();
  32301. var positions = new Array();
  32302. var normals = new Array();
  32303. var uvs = new Array();
  32304. var radius = options.radius || 2;
  32305. var tube = options.tube || 0.5;
  32306. var radialSegments = options.radialSegments || 32;
  32307. var tubularSegments = options.tubularSegments || 32;
  32308. var p = options.p || 2;
  32309. var q = options.q || 3;
  32310. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32311. // Helper
  32312. var getPos = function (angle) {
  32313. var cu = Math.cos(angle);
  32314. var su = Math.sin(angle);
  32315. var quOverP = q / p * angle;
  32316. var cs = Math.cos(quOverP);
  32317. var tx = radius * (2 + cs) * 0.5 * cu;
  32318. var ty = radius * (2 + cs) * su * 0.5;
  32319. var tz = radius * Math.sin(quOverP) * 0.5;
  32320. return new BABYLON.Vector3(tx, ty, tz);
  32321. };
  32322. // Vertices
  32323. var i;
  32324. var j;
  32325. for (i = 0; i <= radialSegments; i++) {
  32326. var modI = i % radialSegments;
  32327. var u = modI / radialSegments * 2 * p * Math.PI;
  32328. var p1 = getPos(u);
  32329. var p2 = getPos(u + 0.01);
  32330. var tang = p2.subtract(p1);
  32331. var n = p2.add(p1);
  32332. var bitan = BABYLON.Vector3.Cross(tang, n);
  32333. n = BABYLON.Vector3.Cross(bitan, tang);
  32334. bitan.normalize();
  32335. n.normalize();
  32336. for (j = 0; j < tubularSegments; j++) {
  32337. var modJ = j % tubularSegments;
  32338. var v = modJ / tubularSegments * 2 * Math.PI;
  32339. var cx = -tube * Math.cos(v);
  32340. var cy = tube * Math.sin(v);
  32341. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32342. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32343. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32344. uvs.push(i / radialSegments);
  32345. uvs.push(j / tubularSegments);
  32346. }
  32347. }
  32348. for (i = 0; i < radialSegments; i++) {
  32349. for (j = 0; j < tubularSegments; j++) {
  32350. var jNext = (j + 1) % tubularSegments;
  32351. var a = i * tubularSegments + j;
  32352. var b = (i + 1) * tubularSegments + j;
  32353. var c = (i + 1) * tubularSegments + jNext;
  32354. var d = i * tubularSegments + jNext;
  32355. indices.push(d);
  32356. indices.push(b);
  32357. indices.push(a);
  32358. indices.push(d);
  32359. indices.push(c);
  32360. indices.push(b);
  32361. }
  32362. }
  32363. // Normals
  32364. VertexData.ComputeNormals(positions, indices, normals);
  32365. // Sides
  32366. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32367. // Result
  32368. var vertexData = new VertexData();
  32369. vertexData.indices = indices;
  32370. vertexData.positions = positions;
  32371. vertexData.normals = normals;
  32372. vertexData.uvs = uvs;
  32373. return vertexData;
  32374. };
  32375. // Tools
  32376. /**
  32377. * @param {any} - positions (number[] or Float32Array)
  32378. * @param {any} - indices (number[] or Uint16Array)
  32379. * @param {any} - normals (number[] or Float32Array)
  32380. * options (optional) :
  32381. * facetPositions : optional array of facet positions (vector3)
  32382. * facetNormals : optional array of facet normals (vector3)
  32383. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32384. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32385. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32386. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32387. * bInfo : optional bounding info, required for facetPartitioning computation
  32388. * useRightHandedSystem: optional boolean to for right handed system computation
  32389. * depthSort : optional boolean to enable the facet depth sort computation
  32390. * distanceTo : optional Vector3 to compute the facet depth from this location
  32391. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32392. */
  32393. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32394. // temporary scalar variables
  32395. var index = 0; // facet index
  32396. var p1p2x = 0.0; // p1p2 vector x coordinate
  32397. var p1p2y = 0.0; // p1p2 vector y coordinate
  32398. var p1p2z = 0.0; // p1p2 vector z coordinate
  32399. var p3p2x = 0.0; // p3p2 vector x coordinate
  32400. var p3p2y = 0.0; // p3p2 vector y coordinate
  32401. var p3p2z = 0.0; // p3p2 vector z coordinate
  32402. var faceNormalx = 0.0; // facet normal x coordinate
  32403. var faceNormaly = 0.0; // facet normal y coordinate
  32404. var faceNormalz = 0.0; // facet normal z coordinate
  32405. var length = 0.0; // facet normal length before normalization
  32406. var v1x = 0; // vector1 x index in the positions array
  32407. var v1y = 0; // vector1 y index in the positions array
  32408. var v1z = 0; // vector1 z index in the positions array
  32409. var v2x = 0; // vector2 x index in the positions array
  32410. var v2y = 0; // vector2 y index in the positions array
  32411. var v2z = 0; // vector2 z index in the positions array
  32412. var v3x = 0; // vector3 x index in the positions array
  32413. var v3y = 0; // vector3 y index in the positions array
  32414. var v3z = 0; // vector3 z index in the positions array
  32415. var computeFacetNormals = false;
  32416. var computeFacetPositions = false;
  32417. var computeFacetPartitioning = false;
  32418. var computeDepthSort = false;
  32419. var faceNormalSign = 1;
  32420. var ratio = 0;
  32421. var distanceTo = null;
  32422. if (options) {
  32423. computeFacetNormals = (options.facetNormals) ? true : false;
  32424. computeFacetPositions = (options.facetPositions) ? true : false;
  32425. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32426. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32427. ratio = options.ratio || 0;
  32428. computeDepthSort = (options.depthSort) ? true : false;
  32429. distanceTo = (options.distanceTo);
  32430. if (computeDepthSort) {
  32431. if (distanceTo === undefined) {
  32432. distanceTo = BABYLON.Vector3.Zero();
  32433. }
  32434. var depthSortedFacets = options.depthSortedFacets;
  32435. }
  32436. }
  32437. // facetPartitioning reinit if needed
  32438. var xSubRatio = 0;
  32439. var ySubRatio = 0;
  32440. var zSubRatio = 0;
  32441. var subSq = 0;
  32442. if (computeFacetPartitioning && options && options.bbSize) {
  32443. var ox = 0; // X partitioning index for facet position
  32444. var oy = 0; // Y partinioning index for facet position
  32445. var oz = 0; // Z partinioning index for facet position
  32446. var b1x = 0; // X partitioning index for facet v1 vertex
  32447. var b1y = 0; // Y partitioning index for facet v1 vertex
  32448. var b1z = 0; // z partitioning index for facet v1 vertex
  32449. var b2x = 0; // X partitioning index for facet v2 vertex
  32450. var b2y = 0; // Y partitioning index for facet v2 vertex
  32451. var b2z = 0; // Z partitioning index for facet v2 vertex
  32452. var b3x = 0; // X partitioning index for facet v3 vertex
  32453. var b3y = 0; // Y partitioning index for facet v3 vertex
  32454. var b3z = 0; // Z partitioning index for facet v3 vertex
  32455. var block_idx_o = 0; // facet barycenter block index
  32456. var block_idx_v1 = 0; // v1 vertex block index
  32457. var block_idx_v2 = 0; // v2 vertex block index
  32458. var block_idx_v3 = 0; // v3 vertex block index
  32459. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32460. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32461. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32462. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32463. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32464. subSq = options.subDiv.max * options.subDiv.max;
  32465. options.facetPartitioning.length = 0;
  32466. }
  32467. // reset the normals
  32468. for (index = 0; index < positions.length; index++) {
  32469. normals[index] = 0.0;
  32470. }
  32471. // Loop : 1 indice triplet = 1 facet
  32472. var nbFaces = (indices.length / 3) | 0;
  32473. for (index = 0; index < nbFaces; index++) {
  32474. // get the indexes of the coordinates of each vertex of the facet
  32475. v1x = indices[index * 3] * 3;
  32476. v1y = v1x + 1;
  32477. v1z = v1x + 2;
  32478. v2x = indices[index * 3 + 1] * 3;
  32479. v2y = v2x + 1;
  32480. v2z = v2x + 2;
  32481. v3x = indices[index * 3 + 2] * 3;
  32482. v3y = v3x + 1;
  32483. v3z = v3x + 2;
  32484. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32485. p1p2y = positions[v1y] - positions[v2y];
  32486. p1p2z = positions[v1z] - positions[v2z];
  32487. p3p2x = positions[v3x] - positions[v2x];
  32488. p3p2y = positions[v3y] - positions[v2y];
  32489. p3p2z = positions[v3z] - positions[v2z];
  32490. // compute the face normal with the cross product
  32491. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32492. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32493. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32494. // normalize this normal and store it in the array facetData
  32495. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32496. length = (length === 0) ? 1.0 : length;
  32497. faceNormalx /= length;
  32498. faceNormaly /= length;
  32499. faceNormalz /= length;
  32500. if (computeFacetNormals && options) {
  32501. options.facetNormals[index].x = faceNormalx;
  32502. options.facetNormals[index].y = faceNormaly;
  32503. options.facetNormals[index].z = faceNormalz;
  32504. }
  32505. if (computeFacetPositions && options) {
  32506. // compute and the facet barycenter coordinates in the array facetPositions
  32507. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32508. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32509. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32510. }
  32511. if (computeFacetPartitioning && options) {
  32512. // store the facet indexes in arrays in the main facetPartitioning array :
  32513. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32514. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32515. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32516. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32517. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32518. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32519. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32520. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32521. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32522. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32523. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32524. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32525. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32526. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32527. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32528. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32529. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32530. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32531. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32532. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32533. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32534. // push each facet index in each block containing the vertex
  32535. options.facetPartitioning[block_idx_v1].push(index);
  32536. if (block_idx_v2 != block_idx_v1) {
  32537. options.facetPartitioning[block_idx_v2].push(index);
  32538. }
  32539. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32540. options.facetPartitioning[block_idx_v3].push(index);
  32541. }
  32542. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32543. options.facetPartitioning[block_idx_o].push(index);
  32544. }
  32545. }
  32546. if (computeDepthSort && options && options.facetPositions) {
  32547. var dsf = depthSortedFacets[index];
  32548. dsf.ind = index * 3;
  32549. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32550. }
  32551. // compute the normals anyway
  32552. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32553. normals[v1y] += faceNormaly;
  32554. normals[v1z] += faceNormalz;
  32555. normals[v2x] += faceNormalx;
  32556. normals[v2y] += faceNormaly;
  32557. normals[v2z] += faceNormalz;
  32558. normals[v3x] += faceNormalx;
  32559. normals[v3y] += faceNormaly;
  32560. normals[v3z] += faceNormalz;
  32561. }
  32562. // last normalization of each normal
  32563. for (index = 0; index < normals.length / 3; index++) {
  32564. faceNormalx = normals[index * 3];
  32565. faceNormaly = normals[index * 3 + 1];
  32566. faceNormalz = normals[index * 3 + 2];
  32567. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32568. length = (length === 0) ? 1.0 : length;
  32569. faceNormalx /= length;
  32570. faceNormaly /= length;
  32571. faceNormalz /= length;
  32572. normals[index * 3] = faceNormalx;
  32573. normals[index * 3 + 1] = faceNormaly;
  32574. normals[index * 3 + 2] = faceNormalz;
  32575. }
  32576. };
  32577. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32578. var li = indices.length;
  32579. var ln = normals.length;
  32580. var i;
  32581. var n;
  32582. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32583. switch (sideOrientation) {
  32584. case BABYLON.Mesh.FRONTSIDE:
  32585. // nothing changed
  32586. break;
  32587. case BABYLON.Mesh.BACKSIDE:
  32588. var tmp;
  32589. // indices
  32590. for (i = 0; i < li; i += 3) {
  32591. tmp = indices[i];
  32592. indices[i] = indices[i + 2];
  32593. indices[i + 2] = tmp;
  32594. }
  32595. // normals
  32596. for (n = 0; n < ln; n++) {
  32597. normals[n] = -normals[n];
  32598. }
  32599. break;
  32600. case BABYLON.Mesh.DOUBLESIDE:
  32601. // positions
  32602. var lp = positions.length;
  32603. var l = lp / 3;
  32604. for (var p = 0; p < lp; p++) {
  32605. positions[lp + p] = positions[p];
  32606. }
  32607. // indices
  32608. for (i = 0; i < li; i += 3) {
  32609. indices[i + li] = indices[i + 2] + l;
  32610. indices[i + 1 + li] = indices[i + 1] + l;
  32611. indices[i + 2 + li] = indices[i] + l;
  32612. }
  32613. // normals
  32614. for (n = 0; n < ln; n++) {
  32615. normals[ln + n] = -normals[n];
  32616. }
  32617. // uvs
  32618. var lu = uvs.length;
  32619. var u = 0;
  32620. for (u = 0; u < lu; u++) {
  32621. uvs[u + lu] = uvs[u];
  32622. }
  32623. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32624. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32625. u = 0;
  32626. for (i = 0; i < lu / 2; i++) {
  32627. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32628. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32629. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32630. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32631. u += 2;
  32632. }
  32633. break;
  32634. }
  32635. };
  32636. /**
  32637. * Creates a new VertexData from the imported parameters.
  32638. */
  32639. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32640. var vertexData = new VertexData();
  32641. // positions
  32642. var positions = parsedVertexData.positions;
  32643. if (positions) {
  32644. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32645. }
  32646. // normals
  32647. var normals = parsedVertexData.normals;
  32648. if (normals) {
  32649. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32650. }
  32651. // tangents
  32652. var tangents = parsedVertexData.tangents;
  32653. if (tangents) {
  32654. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32655. }
  32656. // uvs
  32657. var uvs = parsedVertexData.uvs;
  32658. if (uvs) {
  32659. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32660. }
  32661. // uv2s
  32662. var uv2s = parsedVertexData.uv2s;
  32663. if (uv2s) {
  32664. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32665. }
  32666. // uv3s
  32667. var uv3s = parsedVertexData.uv3s;
  32668. if (uv3s) {
  32669. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32670. }
  32671. // uv4s
  32672. var uv4s = parsedVertexData.uv4s;
  32673. if (uv4s) {
  32674. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32675. }
  32676. // uv5s
  32677. var uv5s = parsedVertexData.uv5s;
  32678. if (uv5s) {
  32679. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32680. }
  32681. // uv6s
  32682. var uv6s = parsedVertexData.uv6s;
  32683. if (uv6s) {
  32684. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32685. }
  32686. // colors
  32687. var colors = parsedVertexData.colors;
  32688. if (colors) {
  32689. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32690. }
  32691. // matricesIndices
  32692. var matricesIndices = parsedVertexData.matricesIndices;
  32693. if (matricesIndices) {
  32694. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32695. }
  32696. // matricesWeights
  32697. var matricesWeights = parsedVertexData.matricesWeights;
  32698. if (matricesWeights) {
  32699. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32700. }
  32701. // indices
  32702. var indices = parsedVertexData.indices;
  32703. if (indices) {
  32704. vertexData.indices = indices;
  32705. }
  32706. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32707. };
  32708. return VertexData;
  32709. }());
  32710. BABYLON.VertexData = VertexData;
  32711. })(BABYLON || (BABYLON = {}));
  32712. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32713. var BABYLON;
  32714. (function (BABYLON) {
  32715. /**
  32716. * Class used to store geometry data (vertex buffers + index buffer)
  32717. */
  32718. var Geometry = /** @class */ (function () {
  32719. /**
  32720. * Creates a new geometry
  32721. * @param id defines the unique ID
  32722. * @param scene defines the hosting scene
  32723. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32724. * @param updatable defines if geometry must be updatable (false by default)
  32725. * @param mesh defines the mesh that will be associated with the geometry
  32726. */
  32727. function Geometry(id, scene, vertexData, updatable, mesh) {
  32728. if (updatable === void 0) { updatable = false; }
  32729. if (mesh === void 0) { mesh = null; }
  32730. /**
  32731. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32732. */
  32733. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32734. this._totalVertices = 0;
  32735. this._isDisposed = false;
  32736. this._indexBufferIsUpdatable = false;
  32737. this.id = id;
  32738. this._engine = scene.getEngine();
  32739. this._meshes = [];
  32740. this._scene = scene;
  32741. //Init vertex buffer cache
  32742. this._vertexBuffers = {};
  32743. this._indices = [];
  32744. this._updatable = updatable;
  32745. // vertexData
  32746. if (vertexData) {
  32747. this.setAllVerticesData(vertexData, updatable);
  32748. }
  32749. else {
  32750. this._totalVertices = 0;
  32751. this._indices = [];
  32752. }
  32753. if (this._engine.getCaps().vertexArrayObject) {
  32754. this._vertexArrayObjects = {};
  32755. }
  32756. // applyToMesh
  32757. if (mesh) {
  32758. if (mesh.getClassName() === "LinesMesh") {
  32759. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32760. this.updateExtend();
  32761. }
  32762. this.applyToMesh(mesh);
  32763. mesh.computeWorldMatrix(true);
  32764. }
  32765. }
  32766. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32767. /**
  32768. * 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
  32769. */
  32770. get: function () {
  32771. return this._boundingBias;
  32772. },
  32773. /**
  32774. * 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
  32775. */
  32776. set: function (value) {
  32777. if (this._boundingBias && this._boundingBias.equals(value)) {
  32778. return;
  32779. }
  32780. this._boundingBias = value.clone();
  32781. this.updateBoundingInfo(true, null);
  32782. },
  32783. enumerable: true,
  32784. configurable: true
  32785. });
  32786. /**
  32787. * Static function used to attach a new empty geometry to a mesh
  32788. * @param mesh defines the mesh to attach the geometry to
  32789. * @returns the new {BABYLON.Geometry}
  32790. */
  32791. Geometry.CreateGeometryForMesh = function (mesh) {
  32792. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32793. geometry.applyToMesh(mesh);
  32794. return geometry;
  32795. };
  32796. Object.defineProperty(Geometry.prototype, "extend", {
  32797. /**
  32798. * Gets the current extend of the geometry
  32799. */
  32800. get: function () {
  32801. return this._extend;
  32802. },
  32803. enumerable: true,
  32804. configurable: true
  32805. });
  32806. /**
  32807. * Gets the hosting scene
  32808. * @returns the hosting {BABYLON.Scene}
  32809. */
  32810. Geometry.prototype.getScene = function () {
  32811. return this._scene;
  32812. };
  32813. /**
  32814. * Gets the hosting engine
  32815. * @returns the hosting {BABYLON.Engine}
  32816. */
  32817. Geometry.prototype.getEngine = function () {
  32818. return this._engine;
  32819. };
  32820. /**
  32821. * Defines if the geometry is ready to use
  32822. * @returns true if the geometry is ready to be used
  32823. */
  32824. Geometry.prototype.isReady = function () {
  32825. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32826. };
  32827. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32828. /**
  32829. * Gets a value indicating that the geometry should not be serialized
  32830. */
  32831. get: function () {
  32832. for (var index = 0; index < this._meshes.length; index++) {
  32833. if (!this._meshes[index].doNotSerialize) {
  32834. return false;
  32835. }
  32836. }
  32837. return true;
  32838. },
  32839. enumerable: true,
  32840. configurable: true
  32841. });
  32842. /** @ignore */
  32843. Geometry.prototype._rebuild = function () {
  32844. if (this._vertexArrayObjects) {
  32845. this._vertexArrayObjects = {};
  32846. }
  32847. // Index buffer
  32848. if (this._meshes.length !== 0 && this._indices) {
  32849. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32850. }
  32851. // Vertex buffers
  32852. for (var key in this._vertexBuffers) {
  32853. var vertexBuffer = this._vertexBuffers[key];
  32854. vertexBuffer._rebuild();
  32855. }
  32856. };
  32857. /**
  32858. * Affects all gemetry data in one call
  32859. * @param vertexData defines the geometry data
  32860. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32861. */
  32862. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32863. vertexData.applyToGeometry(this, updatable);
  32864. this.notifyUpdate();
  32865. };
  32866. /**
  32867. * Set specific vertex data
  32868. * @param kind defines the data kind (Position, normal, etc...)
  32869. * @param data defines the vertex data to use
  32870. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32871. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32872. */
  32873. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32874. if (updatable === void 0) { updatable = false; }
  32875. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32876. this.setVerticesBuffer(buffer);
  32877. };
  32878. /**
  32879. * Removes a specific vertex data
  32880. * @param kind defines the data kind (Position, normal, etc...)
  32881. */
  32882. Geometry.prototype.removeVerticesData = function (kind) {
  32883. if (this._vertexBuffers[kind]) {
  32884. this._vertexBuffers[kind].dispose();
  32885. delete this._vertexBuffers[kind];
  32886. }
  32887. };
  32888. /**
  32889. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32890. * @param buffer defines the vertex buffer to use
  32891. */
  32892. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32893. var kind = buffer.getKind();
  32894. if (this._vertexBuffers[kind]) {
  32895. this._vertexBuffers[kind].dispose();
  32896. }
  32897. this._vertexBuffers[kind] = buffer;
  32898. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32899. var data = buffer.getData();
  32900. var stride = buffer.getStrideSize();
  32901. this._totalVertices = data.length / stride;
  32902. this.updateExtend(data, stride);
  32903. this._resetPointsArrayCache();
  32904. var meshes = this._meshes;
  32905. var numOfMeshes = meshes.length;
  32906. for (var index = 0; index < numOfMeshes; index++) {
  32907. var mesh = meshes[index];
  32908. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32909. mesh._createGlobalSubMesh(false);
  32910. mesh.computeWorldMatrix(true);
  32911. }
  32912. }
  32913. this.notifyUpdate(kind);
  32914. if (this._vertexArrayObjects) {
  32915. this._disposeVertexArrayObjects();
  32916. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32917. }
  32918. };
  32919. /**
  32920. * Update a specific vertex buffer
  32921. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32922. * It will do nothing if the buffer is not updatable
  32923. * @param kind defines the data kind (Position, normal, etc...)
  32924. * @param data defines the data to use
  32925. * @param offset defines the offset in the target buffer where to store the data
  32926. */
  32927. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32928. var vertexBuffer = this.getVertexBuffer(kind);
  32929. if (!vertexBuffer) {
  32930. return;
  32931. }
  32932. vertexBuffer.updateDirectly(data, offset);
  32933. this.notifyUpdate(kind);
  32934. };
  32935. /**
  32936. * Update a specific vertex buffer
  32937. * This function will create a new buffer if the current one is not updatable
  32938. * @param kind defines the data kind (Position, normal, etc...)
  32939. * @param data defines the data to use
  32940. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32941. */
  32942. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32943. if (updateExtends === void 0) { updateExtends = false; }
  32944. var vertexBuffer = this.getVertexBuffer(kind);
  32945. if (!vertexBuffer) {
  32946. return;
  32947. }
  32948. vertexBuffer.update(data);
  32949. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32950. var stride = vertexBuffer.getStrideSize();
  32951. this._totalVertices = data.length / stride;
  32952. this.updateBoundingInfo(updateExtends, data);
  32953. }
  32954. this.notifyUpdate(kind);
  32955. };
  32956. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32957. if (updateExtends) {
  32958. this.updateExtend(data);
  32959. }
  32960. var meshes = this._meshes;
  32961. var numOfMeshes = meshes.length;
  32962. this._resetPointsArrayCache();
  32963. for (var index = 0; index < numOfMeshes; index++) {
  32964. var mesh = meshes[index];
  32965. if (updateExtends) {
  32966. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32967. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32968. var subMesh = mesh.subMeshes[subIndex];
  32969. subMesh.refreshBoundingInfo();
  32970. }
  32971. }
  32972. }
  32973. };
  32974. /** @ignore */
  32975. Geometry.prototype._bind = function (effect, indexToBind) {
  32976. if (!effect) {
  32977. return;
  32978. }
  32979. if (indexToBind === undefined) {
  32980. indexToBind = this._indexBuffer;
  32981. }
  32982. var vbs = this.getVertexBuffers();
  32983. if (!vbs) {
  32984. return;
  32985. }
  32986. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32987. this._engine.bindBuffers(vbs, indexToBind, effect);
  32988. return;
  32989. }
  32990. // Using VAO
  32991. if (!this._vertexArrayObjects[effect.key]) {
  32992. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32993. }
  32994. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32995. };
  32996. /**
  32997. * Gets total number of vertices
  32998. * @returns the total number of vertices
  32999. */
  33000. Geometry.prototype.getTotalVertices = function () {
  33001. if (!this.isReady()) {
  33002. return 0;
  33003. }
  33004. return this._totalVertices;
  33005. };
  33006. /**
  33007. * Gets a specific vertex data attached to this geometry
  33008. * @param kind defines the data kind (Position, normal, etc...)
  33009. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33010. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  33011. * @returns a float array containing vertex data
  33012. */
  33013. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  33014. var vertexBuffer = this.getVertexBuffer(kind);
  33015. if (!vertexBuffer) {
  33016. return null;
  33017. }
  33018. var orig = vertexBuffer.getData();
  33019. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  33020. return orig;
  33021. }
  33022. else {
  33023. var len = orig.length;
  33024. var copy = [];
  33025. for (var i = 0; i < len; i++) {
  33026. copy.push(orig[i]);
  33027. }
  33028. return copy;
  33029. }
  33030. };
  33031. /**
  33032. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  33033. * @param kind defines the data kind (Position, normal, etc...)
  33034. * @returns true if the vertex buffer with the specified kind is updatable
  33035. */
  33036. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  33037. var vb = this._vertexBuffers[kind];
  33038. if (!vb) {
  33039. return false;
  33040. }
  33041. return vb.isUpdatable();
  33042. };
  33043. /**
  33044. * Gets a specific vertex buffer
  33045. * @param kind defines the data kind (Position, normal, etc...)
  33046. * @returns a {BABYLON.VertexBuffer}
  33047. */
  33048. Geometry.prototype.getVertexBuffer = function (kind) {
  33049. if (!this.isReady()) {
  33050. return null;
  33051. }
  33052. return this._vertexBuffers[kind];
  33053. };
  33054. /**
  33055. * Returns all vertex buffers
  33056. * @return an object holding all vertex buffers indexed by kind
  33057. */
  33058. Geometry.prototype.getVertexBuffers = function () {
  33059. if (!this.isReady()) {
  33060. return null;
  33061. }
  33062. return this._vertexBuffers;
  33063. };
  33064. /**
  33065. * Gets a boolean indicating if specific vertex buffer is present
  33066. * @param kind defines the data kind (Position, normal, etc...)
  33067. * @returns true if data is present
  33068. */
  33069. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33070. if (!this._vertexBuffers) {
  33071. if (this._delayInfo) {
  33072. return this._delayInfo.indexOf(kind) !== -1;
  33073. }
  33074. return false;
  33075. }
  33076. return this._vertexBuffers[kind] !== undefined;
  33077. };
  33078. /**
  33079. * Gets a list of all attached data kinds (Position, normal, etc...)
  33080. * @returns a list of string containing all kinds
  33081. */
  33082. Geometry.prototype.getVerticesDataKinds = function () {
  33083. var result = [];
  33084. var kind;
  33085. if (!this._vertexBuffers && this._delayInfo) {
  33086. for (kind in this._delayInfo) {
  33087. result.push(kind);
  33088. }
  33089. }
  33090. else {
  33091. for (kind in this._vertexBuffers) {
  33092. result.push(kind);
  33093. }
  33094. }
  33095. return result;
  33096. };
  33097. /**
  33098. * Update index buffer
  33099. * @param indices defines the indices to store in the index buffer
  33100. * @param offset defines the offset in the target buffer where to store the data
  33101. */
  33102. Geometry.prototype.updateIndices = function (indices, offset) {
  33103. if (!this._indexBuffer) {
  33104. return;
  33105. }
  33106. if (!this._indexBufferIsUpdatable) {
  33107. this.setIndices(indices, null, true);
  33108. }
  33109. else {
  33110. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  33111. }
  33112. };
  33113. /**
  33114. * Creates a new index buffer
  33115. * @param indices defines the indices to store in the index buffer
  33116. * @param totalVertices defines the total number of vertices (could be null)
  33117. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  33118. */
  33119. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  33120. if (totalVertices === void 0) { totalVertices = null; }
  33121. if (updatable === void 0) { updatable = false; }
  33122. if (this._indexBuffer) {
  33123. this._engine._releaseBuffer(this._indexBuffer);
  33124. }
  33125. this._disposeVertexArrayObjects();
  33126. this._indices = indices;
  33127. this._indexBufferIsUpdatable = updatable;
  33128. if (this._meshes.length !== 0 && this._indices) {
  33129. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  33130. }
  33131. if (totalVertices != undefined) {
  33132. this._totalVertices = totalVertices;
  33133. }
  33134. var meshes = this._meshes;
  33135. var numOfMeshes = meshes.length;
  33136. for (var index = 0; index < numOfMeshes; index++) {
  33137. meshes[index]._createGlobalSubMesh(true);
  33138. }
  33139. this.notifyUpdate();
  33140. };
  33141. /**
  33142. * Return the total number of indices
  33143. * @returns the total number of indices
  33144. */
  33145. Geometry.prototype.getTotalIndices = function () {
  33146. if (!this.isReady()) {
  33147. return 0;
  33148. }
  33149. return this._indices.length;
  33150. };
  33151. /**
  33152. * Gets the index buffer array
  33153. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33154. * @returns the index buffer array
  33155. */
  33156. Geometry.prototype.getIndices = function (copyWhenShared) {
  33157. if (!this.isReady()) {
  33158. return null;
  33159. }
  33160. var orig = this._indices;
  33161. if (!copyWhenShared || this._meshes.length === 1) {
  33162. return orig;
  33163. }
  33164. else {
  33165. var len = orig.length;
  33166. var copy = [];
  33167. for (var i = 0; i < len; i++) {
  33168. copy.push(orig[i]);
  33169. }
  33170. return copy;
  33171. }
  33172. };
  33173. /**
  33174. * Gets the index buffer
  33175. * @return the index buffer
  33176. */
  33177. Geometry.prototype.getIndexBuffer = function () {
  33178. if (!this.isReady()) {
  33179. return null;
  33180. }
  33181. return this._indexBuffer;
  33182. };
  33183. /** @ignore */
  33184. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  33185. if (effect === void 0) { effect = null; }
  33186. if (!effect || !this._vertexArrayObjects) {
  33187. return;
  33188. }
  33189. if (this._vertexArrayObjects[effect.key]) {
  33190. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  33191. delete this._vertexArrayObjects[effect.key];
  33192. }
  33193. };
  33194. /**
  33195. * Release the associated resources for a specific mesh
  33196. * @param mesh defines the source mesh
  33197. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  33198. */
  33199. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33200. var meshes = this._meshes;
  33201. var index = meshes.indexOf(mesh);
  33202. if (index === -1) {
  33203. return;
  33204. }
  33205. meshes.splice(index, 1);
  33206. mesh._geometry = null;
  33207. if (meshes.length === 0 && shouldDispose) {
  33208. this.dispose();
  33209. }
  33210. };
  33211. /**
  33212. * Apply current geometry to a given mesh
  33213. * @param mesh defines the mesh to apply geometry to
  33214. */
  33215. Geometry.prototype.applyToMesh = function (mesh) {
  33216. if (mesh._geometry === this) {
  33217. return;
  33218. }
  33219. var previousGeometry = mesh._geometry;
  33220. if (previousGeometry) {
  33221. previousGeometry.releaseForMesh(mesh);
  33222. }
  33223. var meshes = this._meshes;
  33224. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33225. mesh._geometry = this;
  33226. this._scene.pushGeometry(this);
  33227. meshes.push(mesh);
  33228. if (this.isReady()) {
  33229. this._applyToMesh(mesh);
  33230. }
  33231. else {
  33232. mesh._boundingInfo = this._boundingInfo;
  33233. }
  33234. };
  33235. Geometry.prototype.updateExtend = function (data, stride) {
  33236. if (data === void 0) { data = null; }
  33237. if (!data) {
  33238. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33239. }
  33240. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33241. };
  33242. Geometry.prototype._applyToMesh = function (mesh) {
  33243. var numOfMeshes = this._meshes.length;
  33244. // vertexBuffers
  33245. for (var kind in this._vertexBuffers) {
  33246. if (numOfMeshes === 1) {
  33247. this._vertexBuffers[kind].create();
  33248. }
  33249. var buffer = this._vertexBuffers[kind].getBuffer();
  33250. if (buffer)
  33251. buffer.references = numOfMeshes;
  33252. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33253. if (!this._extend) {
  33254. this.updateExtend(this._vertexBuffers[kind].getData());
  33255. }
  33256. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33257. mesh._createGlobalSubMesh(false);
  33258. //bounding info was just created again, world matrix should be applied again.
  33259. mesh._updateBoundingInfo();
  33260. }
  33261. }
  33262. // indexBuffer
  33263. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33264. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33265. }
  33266. if (this._indexBuffer) {
  33267. this._indexBuffer.references = numOfMeshes;
  33268. }
  33269. };
  33270. Geometry.prototype.notifyUpdate = function (kind) {
  33271. if (this.onGeometryUpdated) {
  33272. this.onGeometryUpdated(this, kind);
  33273. }
  33274. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33275. var mesh = _a[_i];
  33276. mesh._markSubMeshesAsAttributesDirty();
  33277. }
  33278. };
  33279. /**
  33280. * Load the geometry if it was flagged as delay loaded
  33281. * @param scene defines the hosting scene
  33282. * @param onLoaded defines a callback called when the geometry is loaded
  33283. */
  33284. Geometry.prototype.load = function (scene, onLoaded) {
  33285. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33286. return;
  33287. }
  33288. if (this.isReady()) {
  33289. if (onLoaded) {
  33290. onLoaded();
  33291. }
  33292. return;
  33293. }
  33294. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33295. this._queueLoad(scene, onLoaded);
  33296. };
  33297. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33298. var _this = this;
  33299. if (!this.delayLoadingFile) {
  33300. return;
  33301. }
  33302. scene._addPendingData(this);
  33303. scene._loadFile(this.delayLoadingFile, function (data) {
  33304. if (!_this._delayLoadingFunction) {
  33305. return;
  33306. }
  33307. _this._delayLoadingFunction(JSON.parse(data), _this);
  33308. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33309. _this._delayInfo = [];
  33310. scene._removePendingData(_this);
  33311. var meshes = _this._meshes;
  33312. var numOfMeshes = meshes.length;
  33313. for (var index = 0; index < numOfMeshes; index++) {
  33314. _this._applyToMesh(meshes[index]);
  33315. }
  33316. if (onLoaded) {
  33317. onLoaded();
  33318. }
  33319. }, undefined, true);
  33320. };
  33321. /**
  33322. * Invert the geometry to move from a right handed system to a left handed one.
  33323. */
  33324. Geometry.prototype.toLeftHanded = function () {
  33325. // Flip faces
  33326. var tIndices = this.getIndices(false);
  33327. if (tIndices != null && tIndices.length > 0) {
  33328. for (var i = 0; i < tIndices.length; i += 3) {
  33329. var tTemp = tIndices[i + 0];
  33330. tIndices[i + 0] = tIndices[i + 2];
  33331. tIndices[i + 2] = tTemp;
  33332. }
  33333. this.setIndices(tIndices);
  33334. }
  33335. // Negate position.z
  33336. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33337. if (tPositions != null && tPositions.length > 0) {
  33338. for (var i = 0; i < tPositions.length; i += 3) {
  33339. tPositions[i + 2] = -tPositions[i + 2];
  33340. }
  33341. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33342. }
  33343. // Negate normal.z
  33344. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33345. if (tNormals != null && tNormals.length > 0) {
  33346. for (var i = 0; i < tNormals.length; i += 3) {
  33347. tNormals[i + 2] = -tNormals[i + 2];
  33348. }
  33349. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33350. }
  33351. };
  33352. // Cache
  33353. /** @ignore */
  33354. Geometry.prototype._resetPointsArrayCache = function () {
  33355. this._positions = null;
  33356. };
  33357. /** @ignore */
  33358. Geometry.prototype._generatePointsArray = function () {
  33359. if (this._positions)
  33360. return true;
  33361. this._positions = [];
  33362. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33363. if (!data) {
  33364. return false;
  33365. }
  33366. for (var index = 0; index < data.length; index += 3) {
  33367. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33368. }
  33369. return true;
  33370. };
  33371. /**
  33372. * Gets a value indicating if the geometry is disposed
  33373. * @returns true if the geometry was disposed
  33374. */
  33375. Geometry.prototype.isDisposed = function () {
  33376. return this._isDisposed;
  33377. };
  33378. Geometry.prototype._disposeVertexArrayObjects = function () {
  33379. if (this._vertexArrayObjects) {
  33380. for (var kind in this._vertexArrayObjects) {
  33381. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33382. }
  33383. this._vertexArrayObjects = {};
  33384. }
  33385. };
  33386. /**
  33387. * Free all associated resources
  33388. */
  33389. Geometry.prototype.dispose = function () {
  33390. var meshes = this._meshes;
  33391. var numOfMeshes = meshes.length;
  33392. var index;
  33393. for (index = 0; index < numOfMeshes; index++) {
  33394. this.releaseForMesh(meshes[index]);
  33395. }
  33396. this._meshes = [];
  33397. this._disposeVertexArrayObjects();
  33398. for (var kind in this._vertexBuffers) {
  33399. this._vertexBuffers[kind].dispose();
  33400. }
  33401. this._vertexBuffers = {};
  33402. this._totalVertices = 0;
  33403. if (this._indexBuffer) {
  33404. this._engine._releaseBuffer(this._indexBuffer);
  33405. }
  33406. this._indexBuffer = null;
  33407. this._indices = [];
  33408. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33409. this.delayLoadingFile = null;
  33410. this._delayLoadingFunction = null;
  33411. this._delayInfo = [];
  33412. this._boundingInfo = null;
  33413. this._scene.removeGeometry(this);
  33414. this._isDisposed = true;
  33415. };
  33416. /**
  33417. * Clone the current geometry into a new geometry
  33418. * @param id defines the unique ID of the new geometry
  33419. * @returns a new geometry object
  33420. */
  33421. Geometry.prototype.copy = function (id) {
  33422. var vertexData = new BABYLON.VertexData();
  33423. vertexData.indices = [];
  33424. var indices = this.getIndices();
  33425. if (indices) {
  33426. for (var index = 0; index < indices.length; index++) {
  33427. vertexData.indices.push(indices[index]);
  33428. }
  33429. }
  33430. var updatable = false;
  33431. var stopChecking = false;
  33432. var kind;
  33433. for (kind in this._vertexBuffers) {
  33434. // using slice() to make a copy of the array and not just reference it
  33435. var data = this.getVerticesData(kind);
  33436. if (data instanceof Float32Array) {
  33437. vertexData.set(new Float32Array(data), kind);
  33438. }
  33439. else {
  33440. vertexData.set(data.slice(0), kind);
  33441. }
  33442. if (!stopChecking) {
  33443. var vb = this.getVertexBuffer(kind);
  33444. if (vb) {
  33445. updatable = vb.isUpdatable();
  33446. stopChecking = !updatable;
  33447. }
  33448. }
  33449. }
  33450. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33451. geometry.delayLoadState = this.delayLoadState;
  33452. geometry.delayLoadingFile = this.delayLoadingFile;
  33453. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33454. for (kind in this._delayInfo) {
  33455. geometry._delayInfo = geometry._delayInfo || [];
  33456. geometry._delayInfo.push(kind);
  33457. }
  33458. // Bounding info
  33459. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33460. return geometry;
  33461. };
  33462. /**
  33463. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33464. * @return a JSON representation of the current geometry data (without the vertices data)
  33465. */
  33466. Geometry.prototype.serialize = function () {
  33467. var serializationObject = {};
  33468. serializationObject.id = this.id;
  33469. serializationObject.updatable = this._updatable;
  33470. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33471. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33472. }
  33473. return serializationObject;
  33474. };
  33475. Geometry.prototype.toNumberArray = function (origin) {
  33476. if (Array.isArray(origin)) {
  33477. return origin;
  33478. }
  33479. else {
  33480. return Array.prototype.slice.call(origin);
  33481. }
  33482. };
  33483. /**
  33484. * Serialize all vertices data into a JSON oject
  33485. * @returns a JSON representation of the current geometry data
  33486. */
  33487. Geometry.prototype.serializeVerticeData = function () {
  33488. var serializationObject = this.serialize();
  33489. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33490. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33491. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33492. serializationObject.positions._updatable = true;
  33493. }
  33494. }
  33495. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33496. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33497. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33498. serializationObject.normals._updatable = true;
  33499. }
  33500. }
  33501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33502. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33503. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33504. serializationObject.tangets._updatable = true;
  33505. }
  33506. }
  33507. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33508. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33509. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33510. serializationObject.uvs._updatable = true;
  33511. }
  33512. }
  33513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33514. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33515. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33516. serializationObject.uv2s._updatable = true;
  33517. }
  33518. }
  33519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33520. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33521. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33522. serializationObject.uv3s._updatable = true;
  33523. }
  33524. }
  33525. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33526. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33527. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33528. serializationObject.uv4s._updatable = true;
  33529. }
  33530. }
  33531. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33532. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33533. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33534. serializationObject.uv5s._updatable = true;
  33535. }
  33536. }
  33537. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33538. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33539. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33540. serializationObject.uv6s._updatable = true;
  33541. }
  33542. }
  33543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33544. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33545. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33546. serializationObject.colors._updatable = true;
  33547. }
  33548. }
  33549. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33550. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33551. serializationObject.matricesIndices._isExpanded = true;
  33552. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33553. serializationObject.matricesIndices._updatable = true;
  33554. }
  33555. }
  33556. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33557. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33558. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33559. serializationObject.matricesWeights._updatable = true;
  33560. }
  33561. }
  33562. serializationObject.indices = this.toNumberArray(this.getIndices());
  33563. return serializationObject;
  33564. };
  33565. // Statics
  33566. /**
  33567. * Extracts a clone of a mesh geometry
  33568. * @param mesh defines the source mesh
  33569. * @param id defines the unique ID of the new geometry object
  33570. * @returns the new geometry object
  33571. */
  33572. Geometry.ExtractFromMesh = function (mesh, id) {
  33573. var geometry = mesh._geometry;
  33574. if (!geometry) {
  33575. return null;
  33576. }
  33577. return geometry.copy(id);
  33578. };
  33579. /**
  33580. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33581. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33582. * Be aware Math.random() could cause collisions, but:
  33583. * "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"
  33584. * @returns a string containing a new GUID
  33585. */
  33586. Geometry.RandomId = function () {
  33587. return BABYLON.Tools.RandomId();
  33588. };
  33589. /** @ignore */
  33590. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33591. var scene = mesh.getScene();
  33592. // Geometry
  33593. var geometryId = parsedGeometry.geometryId;
  33594. if (geometryId) {
  33595. var geometry = scene.getGeometryByID(geometryId);
  33596. if (geometry) {
  33597. geometry.applyToMesh(mesh);
  33598. }
  33599. }
  33600. else if (parsedGeometry instanceof ArrayBuffer) {
  33601. var binaryInfo = mesh._binaryInfo;
  33602. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33603. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33604. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33605. }
  33606. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33607. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33608. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33609. }
  33610. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33611. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33612. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33613. }
  33614. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33615. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33616. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33617. }
  33618. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33619. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33620. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33621. }
  33622. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33623. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33624. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33625. }
  33626. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33627. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33628. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33629. }
  33630. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33631. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33632. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33633. }
  33634. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33635. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33636. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33637. }
  33638. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33639. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33640. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33641. }
  33642. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33643. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33644. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33645. }
  33646. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33647. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33648. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33649. }
  33650. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33651. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33652. mesh.setIndices(indicesData, null);
  33653. }
  33654. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33655. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33656. mesh.subMeshes = [];
  33657. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33658. var materialIndex = subMeshesData[(i * 5) + 0];
  33659. var verticesStart = subMeshesData[(i * 5) + 1];
  33660. var verticesCount = subMeshesData[(i * 5) + 2];
  33661. var indexStart = subMeshesData[(i * 5) + 3];
  33662. var indexCount = subMeshesData[(i * 5) + 4];
  33663. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33664. }
  33665. }
  33666. }
  33667. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33668. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33669. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33670. if (parsedGeometry.tangents) {
  33671. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33672. }
  33673. if (parsedGeometry.uvs) {
  33674. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33675. }
  33676. if (parsedGeometry.uvs2) {
  33677. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33678. }
  33679. if (parsedGeometry.uvs3) {
  33680. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33681. }
  33682. if (parsedGeometry.uvs4) {
  33683. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33684. }
  33685. if (parsedGeometry.uvs5) {
  33686. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33687. }
  33688. if (parsedGeometry.uvs6) {
  33689. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33690. }
  33691. if (parsedGeometry.colors) {
  33692. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33693. }
  33694. if (parsedGeometry.matricesIndices) {
  33695. if (!parsedGeometry.matricesIndices._isExpanded) {
  33696. var floatIndices = [];
  33697. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33698. var matricesIndex = parsedGeometry.matricesIndices[i];
  33699. floatIndices.push(matricesIndex & 0x000000FF);
  33700. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33701. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33702. floatIndices.push(matricesIndex >> 24);
  33703. }
  33704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33705. }
  33706. else {
  33707. delete parsedGeometry.matricesIndices._isExpanded;
  33708. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33709. }
  33710. }
  33711. if (parsedGeometry.matricesIndicesExtra) {
  33712. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33713. var floatIndices = [];
  33714. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33715. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33716. floatIndices.push(matricesIndex & 0x000000FF);
  33717. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33718. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33719. floatIndices.push(matricesIndex >> 24);
  33720. }
  33721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33722. }
  33723. else {
  33724. delete parsedGeometry.matricesIndices._isExpanded;
  33725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33726. }
  33727. }
  33728. if (parsedGeometry.matricesWeights) {
  33729. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33730. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33731. }
  33732. if (parsedGeometry.matricesWeightsExtra) {
  33733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33734. }
  33735. mesh.setIndices(parsedGeometry.indices, null);
  33736. }
  33737. // SubMeshes
  33738. if (parsedGeometry.subMeshes) {
  33739. mesh.subMeshes = [];
  33740. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33741. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33742. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33743. }
  33744. }
  33745. // Flat shading
  33746. if (mesh._shouldGenerateFlatShading) {
  33747. mesh.convertToFlatShadedMesh();
  33748. delete mesh._shouldGenerateFlatShading;
  33749. }
  33750. // Update
  33751. mesh.computeWorldMatrix(true);
  33752. // Octree
  33753. var sceneOctree = scene.selectionOctree;
  33754. if (sceneOctree !== undefined && sceneOctree !== null) {
  33755. sceneOctree.addMesh(mesh);
  33756. }
  33757. };
  33758. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33759. var epsilon = 1e-3;
  33760. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33761. return;
  33762. }
  33763. var noInfluenceBoneIndex = 0.0;
  33764. if (parsedGeometry.skeletonId > -1) {
  33765. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33766. if (!skeleton) {
  33767. return;
  33768. }
  33769. noInfluenceBoneIndex = skeleton.bones.length;
  33770. }
  33771. else {
  33772. return;
  33773. }
  33774. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33775. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33776. var matricesWeights = parsedGeometry.matricesWeights;
  33777. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33778. var influencers = parsedGeometry.numBoneInfluencer;
  33779. var size = matricesWeights.length;
  33780. for (var i = 0; i < size; i += 4) {
  33781. var weight = 0.0;
  33782. var firstZeroWeight = -1;
  33783. for (var j = 0; j < 4; j++) {
  33784. var w = matricesWeights[i + j];
  33785. weight += w;
  33786. if (w < epsilon && firstZeroWeight < 0) {
  33787. firstZeroWeight = j;
  33788. }
  33789. }
  33790. if (matricesWeightsExtra) {
  33791. for (var j = 0; j < 4; j++) {
  33792. var w = matricesWeightsExtra[i + j];
  33793. weight += w;
  33794. if (w < epsilon && firstZeroWeight < 0) {
  33795. firstZeroWeight = j + 4;
  33796. }
  33797. }
  33798. }
  33799. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33800. firstZeroWeight = influencers - 1;
  33801. }
  33802. if (weight > epsilon) {
  33803. var mweight = 1.0 / weight;
  33804. for (var j = 0; j < 4; j++) {
  33805. matricesWeights[i + j] *= mweight;
  33806. }
  33807. if (matricesWeightsExtra) {
  33808. for (var j = 0; j < 4; j++) {
  33809. matricesWeightsExtra[i + j] *= mweight;
  33810. }
  33811. }
  33812. }
  33813. else {
  33814. if (firstZeroWeight >= 4) {
  33815. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33816. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33817. }
  33818. else {
  33819. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33820. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33821. }
  33822. }
  33823. }
  33824. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33825. if (parsedGeometry.matricesWeightsExtra) {
  33826. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33827. }
  33828. };
  33829. /**
  33830. * Create a new geometry from persisted data (Using .babylon file format)
  33831. * @param parsedVertexData defines the persisted data
  33832. * @param scene defines the hosting scene
  33833. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33834. * @returns the new geometry object
  33835. */
  33836. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33837. if (scene.getGeometryByID(parsedVertexData.id)) {
  33838. return null; // null since geometry could be something else than a box...
  33839. }
  33840. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33841. if (BABYLON.Tags) {
  33842. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33843. }
  33844. if (parsedVertexData.delayLoadingFile) {
  33845. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33846. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33847. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33848. geometry._delayInfo = [];
  33849. if (parsedVertexData.hasUVs) {
  33850. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33851. }
  33852. if (parsedVertexData.hasUVs2) {
  33853. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33854. }
  33855. if (parsedVertexData.hasUVs3) {
  33856. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33857. }
  33858. if (parsedVertexData.hasUVs4) {
  33859. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33860. }
  33861. if (parsedVertexData.hasUVs5) {
  33862. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33863. }
  33864. if (parsedVertexData.hasUVs6) {
  33865. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33866. }
  33867. if (parsedVertexData.hasColors) {
  33868. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33869. }
  33870. if (parsedVertexData.hasMatricesIndices) {
  33871. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33872. }
  33873. if (parsedVertexData.hasMatricesWeights) {
  33874. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33875. }
  33876. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33877. }
  33878. else {
  33879. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33880. }
  33881. scene.pushGeometry(geometry, true);
  33882. return geometry;
  33883. };
  33884. return Geometry;
  33885. }());
  33886. BABYLON.Geometry = Geometry;
  33887. // Primitives
  33888. /// Abstract class
  33889. /**
  33890. * Abstract class used to provide common services for all typed geometries
  33891. */
  33892. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33893. __extends(_PrimitiveGeometry, _super);
  33894. /**
  33895. * Creates a new typed geometry
  33896. * @param id defines the unique ID of the geometry
  33897. * @param scene defines the hosting scene
  33898. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33899. * @param mesh defines the hosting mesh (can be null)
  33900. */
  33901. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33902. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33903. if (mesh === void 0) { mesh = null; }
  33904. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33905. _this._canBeRegenerated = _canBeRegenerated;
  33906. _this._beingRegenerated = true;
  33907. _this.regenerate();
  33908. _this._beingRegenerated = false;
  33909. return _this;
  33910. }
  33911. /**
  33912. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33913. * @returns true if the geometry can be regenerated
  33914. */
  33915. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33916. return this._canBeRegenerated;
  33917. };
  33918. /**
  33919. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33920. */
  33921. _PrimitiveGeometry.prototype.regenerate = function () {
  33922. if (!this._canBeRegenerated) {
  33923. return;
  33924. }
  33925. this._beingRegenerated = true;
  33926. this.setAllVerticesData(this._regenerateVertexData(), false);
  33927. this._beingRegenerated = false;
  33928. };
  33929. /**
  33930. * Clone the geometry
  33931. * @param id defines the unique ID of the new geometry
  33932. * @returns the new geometry
  33933. */
  33934. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33935. return _super.prototype.copy.call(this, id);
  33936. };
  33937. // overrides
  33938. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33939. if (!this._beingRegenerated) {
  33940. return;
  33941. }
  33942. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33943. };
  33944. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33945. if (!this._beingRegenerated) {
  33946. return;
  33947. }
  33948. _super.prototype.setVerticesData.call(this, kind, data, false);
  33949. };
  33950. // to override
  33951. /** @ignore */
  33952. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33953. throw new Error("Abstract method");
  33954. };
  33955. _PrimitiveGeometry.prototype.copy = function (id) {
  33956. throw new Error("Must be overriden in sub-classes.");
  33957. };
  33958. _PrimitiveGeometry.prototype.serialize = function () {
  33959. var serializationObject = _super.prototype.serialize.call(this);
  33960. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33961. return serializationObject;
  33962. };
  33963. return _PrimitiveGeometry;
  33964. }(Geometry));
  33965. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33966. /**
  33967. * Creates a ribbon geometry
  33968. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33969. */
  33970. var RibbonGeometry = /** @class */ (function (_super) {
  33971. __extends(RibbonGeometry, _super);
  33972. /**
  33973. * Creates a ribbon geometry
  33974. * @param id defines the unique ID of the geometry
  33975. * @param scene defines the hosting scene
  33976. * @param pathArray defines the array of paths to use
  33977. * @param closeArray defines if the last path and the first path must be joined
  33978. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33979. * @param offset defines the offset between points
  33980. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33981. * @param mesh defines the hosting mesh (can be null)
  33982. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33983. */
  33984. function RibbonGeometry(id, scene,
  33985. /**
  33986. * Defines the array of paths to use
  33987. */
  33988. pathArray,
  33989. /**
  33990. * Defines if the last and first points of each path in your pathArray must be joined
  33991. */
  33992. closeArray,
  33993. /**
  33994. * Defines if the last and first points of each path in your pathArray must be joined
  33995. */
  33996. closePath,
  33997. /**
  33998. * Defines the offset between points
  33999. */
  34000. offset, canBeRegenerated, mesh,
  34001. /**
  34002. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34003. */
  34004. side) {
  34005. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34006. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34007. _this.pathArray = pathArray;
  34008. _this.closeArray = closeArray;
  34009. _this.closePath = closePath;
  34010. _this.offset = offset;
  34011. _this.side = side;
  34012. return _this;
  34013. }
  34014. /** @ignore */
  34015. RibbonGeometry.prototype._regenerateVertexData = function () {
  34016. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34017. };
  34018. RibbonGeometry.prototype.copy = function (id) {
  34019. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  34020. };
  34021. return RibbonGeometry;
  34022. }(_PrimitiveGeometry));
  34023. BABYLON.RibbonGeometry = RibbonGeometry;
  34024. /**
  34025. * Creates a box geometry
  34026. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  34027. */
  34028. var BoxGeometry = /** @class */ (function (_super) {
  34029. __extends(BoxGeometry, _super);
  34030. /**
  34031. * Creates a box geometry
  34032. * @param id defines the unique ID of the geometry
  34033. * @param scene defines the hosting scene
  34034. * @param size defines the zise of the box (width, height and depth are the same)
  34035. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34036. * @param mesh defines the hosting mesh (can be null)
  34037. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34038. */
  34039. function BoxGeometry(id, scene,
  34040. /**
  34041. * Defines the zise of the box (width, height and depth are the same)
  34042. */
  34043. size, canBeRegenerated, mesh,
  34044. /**
  34045. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34046. */
  34047. side) {
  34048. if (mesh === void 0) { mesh = null; }
  34049. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34050. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34051. _this.size = size;
  34052. _this.side = side;
  34053. return _this;
  34054. }
  34055. BoxGeometry.prototype._regenerateVertexData = function () {
  34056. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34057. };
  34058. BoxGeometry.prototype.copy = function (id) {
  34059. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  34060. };
  34061. BoxGeometry.prototype.serialize = function () {
  34062. var serializationObject = _super.prototype.serialize.call(this);
  34063. serializationObject.size = this.size;
  34064. return serializationObject;
  34065. };
  34066. BoxGeometry.Parse = function (parsedBox, scene) {
  34067. if (scene.getGeometryByID(parsedBox.id)) {
  34068. return null; // null since geometry could be something else than a box...
  34069. }
  34070. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34071. if (BABYLON.Tags) {
  34072. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34073. }
  34074. scene.pushGeometry(box, true);
  34075. return box;
  34076. };
  34077. return BoxGeometry;
  34078. }(_PrimitiveGeometry));
  34079. BABYLON.BoxGeometry = BoxGeometry;
  34080. /**
  34081. * Creates a sphere geometry
  34082. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  34083. */
  34084. var SphereGeometry = /** @class */ (function (_super) {
  34085. __extends(SphereGeometry, _super);
  34086. /**
  34087. * Create a new sphere geometry
  34088. * @param id defines the unique ID of the geometry
  34089. * @param scene defines the hosting scene
  34090. * @param segments defines the number of segments to use to create the sphere
  34091. * @param diameter defines the diameter of the sphere
  34092. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34093. * @param mesh defines the hosting mesh (can be null)
  34094. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34095. */
  34096. function SphereGeometry(id, scene,
  34097. /**
  34098. * Defines the number of segments to use to create the sphere
  34099. */
  34100. segments,
  34101. /**
  34102. * Defines the diameter of the sphere
  34103. */
  34104. diameter, canBeRegenerated, mesh,
  34105. /**
  34106. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34107. */
  34108. side) {
  34109. if (mesh === void 0) { mesh = null; }
  34110. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34111. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34112. _this.segments = segments;
  34113. _this.diameter = diameter;
  34114. _this.side = side;
  34115. return _this;
  34116. }
  34117. SphereGeometry.prototype._regenerateVertexData = function () {
  34118. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34119. };
  34120. SphereGeometry.prototype.copy = function (id) {
  34121. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34122. };
  34123. SphereGeometry.prototype.serialize = function () {
  34124. var serializationObject = _super.prototype.serialize.call(this);
  34125. serializationObject.segments = this.segments;
  34126. serializationObject.diameter = this.diameter;
  34127. return serializationObject;
  34128. };
  34129. SphereGeometry.Parse = function (parsedSphere, scene) {
  34130. if (scene.getGeometryByID(parsedSphere.id)) {
  34131. return null; // null since geometry could be something else than a sphere...
  34132. }
  34133. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34134. if (BABYLON.Tags) {
  34135. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34136. }
  34137. scene.pushGeometry(sphere, true);
  34138. return sphere;
  34139. };
  34140. return SphereGeometry;
  34141. }(_PrimitiveGeometry));
  34142. BABYLON.SphereGeometry = SphereGeometry;
  34143. /**
  34144. * Creates a disc geometry
  34145. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  34146. */
  34147. var DiscGeometry = /** @class */ (function (_super) {
  34148. __extends(DiscGeometry, _super);
  34149. /**
  34150. * Creates a new disc geometry
  34151. * @param id defines the unique ID of the geometry
  34152. * @param scene defines the hosting scene
  34153. * @param radius defines the radius of the disc
  34154. * @param tessellation defines the tesselation factor to apply to the disc
  34155. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34156. * @param mesh defines the hosting mesh (can be null)
  34157. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34158. */
  34159. function DiscGeometry(id, scene,
  34160. /**
  34161. * Defines the radius of the disc
  34162. */
  34163. radius,
  34164. /**
  34165. * Defines the tesselation factor to apply to the disc
  34166. */
  34167. tessellation, canBeRegenerated, mesh,
  34168. /**
  34169. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34170. */
  34171. side) {
  34172. if (mesh === void 0) { mesh = null; }
  34173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34175. _this.radius = radius;
  34176. _this.tessellation = tessellation;
  34177. _this.side = side;
  34178. return _this;
  34179. }
  34180. DiscGeometry.prototype._regenerateVertexData = function () {
  34181. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34182. };
  34183. DiscGeometry.prototype.copy = function (id) {
  34184. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34185. };
  34186. return DiscGeometry;
  34187. }(_PrimitiveGeometry));
  34188. BABYLON.DiscGeometry = DiscGeometry;
  34189. /**
  34190. * Creates a new cylinder geometry
  34191. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  34192. */
  34193. var CylinderGeometry = /** @class */ (function (_super) {
  34194. __extends(CylinderGeometry, _super);
  34195. /**
  34196. * Creates a new cylinder geometry
  34197. * @param id defines the unique ID of the geometry
  34198. * @param scene defines the hosting scene
  34199. * @param height defines the height of the cylinder
  34200. * @param diameterTop defines the diameter of the cylinder's top cap
  34201. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  34202. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  34203. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  34204. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34205. * @param mesh defines the hosting mesh (can be null)
  34206. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34207. */
  34208. function CylinderGeometry(id, scene,
  34209. /**
  34210. * Defines the height of the cylinder
  34211. */
  34212. height,
  34213. /**
  34214. * Defines the diameter of the cylinder's top cap
  34215. */
  34216. diameterTop,
  34217. /**
  34218. * Defines the diameter of the cylinder's bottom cap
  34219. */
  34220. diameterBottom,
  34221. /**
  34222. * Defines the tessellation factor to apply to the cylinder
  34223. */
  34224. tessellation,
  34225. /**
  34226. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  34227. */
  34228. subdivisions, canBeRegenerated, mesh,
  34229. /**
  34230. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34231. */
  34232. side) {
  34233. if (subdivisions === void 0) { subdivisions = 1; }
  34234. if (mesh === void 0) { mesh = null; }
  34235. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34236. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34237. _this.height = height;
  34238. _this.diameterTop = diameterTop;
  34239. _this.diameterBottom = diameterBottom;
  34240. _this.tessellation = tessellation;
  34241. _this.subdivisions = subdivisions;
  34242. _this.side = side;
  34243. return _this;
  34244. }
  34245. CylinderGeometry.prototype._regenerateVertexData = function () {
  34246. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34247. };
  34248. CylinderGeometry.prototype.copy = function (id) {
  34249. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34250. };
  34251. CylinderGeometry.prototype.serialize = function () {
  34252. var serializationObject = _super.prototype.serialize.call(this);
  34253. serializationObject.height = this.height;
  34254. serializationObject.diameterTop = this.diameterTop;
  34255. serializationObject.diameterBottom = this.diameterBottom;
  34256. serializationObject.tessellation = this.tessellation;
  34257. return serializationObject;
  34258. };
  34259. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34260. if (scene.getGeometryByID(parsedCylinder.id)) {
  34261. return null; // null since geometry could be something else than a cylinder...
  34262. }
  34263. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34264. if (BABYLON.Tags) {
  34265. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34266. }
  34267. scene.pushGeometry(cylinder, true);
  34268. return cylinder;
  34269. };
  34270. return CylinderGeometry;
  34271. }(_PrimitiveGeometry));
  34272. BABYLON.CylinderGeometry = CylinderGeometry;
  34273. /**
  34274. * Creates a new torus geometry
  34275. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34276. */
  34277. var TorusGeometry = /** @class */ (function (_super) {
  34278. __extends(TorusGeometry, _super);
  34279. /**
  34280. * Creates a new torus geometry
  34281. * @param id defines the unique ID of the geometry
  34282. * @param scene defines the hosting scene
  34283. * @param diameter defines the diameter of the torus
  34284. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34285. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34286. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34287. * @param mesh defines the hosting mesh (can be null)
  34288. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34289. */
  34290. function TorusGeometry(id, scene,
  34291. /**
  34292. * Defines the diameter of the torus
  34293. */
  34294. diameter,
  34295. /**
  34296. * Defines the thickness of the torus (ie. internal diameter)
  34297. */
  34298. thickness,
  34299. /**
  34300. * Defines the tesselation factor to apply to the torus
  34301. */
  34302. tessellation, canBeRegenerated, mesh,
  34303. /**
  34304. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34305. */
  34306. side) {
  34307. if (mesh === void 0) { mesh = null; }
  34308. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34309. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34310. _this.diameter = diameter;
  34311. _this.thickness = thickness;
  34312. _this.tessellation = tessellation;
  34313. _this.side = side;
  34314. return _this;
  34315. }
  34316. TorusGeometry.prototype._regenerateVertexData = function () {
  34317. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34318. };
  34319. TorusGeometry.prototype.copy = function (id) {
  34320. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34321. };
  34322. TorusGeometry.prototype.serialize = function () {
  34323. var serializationObject = _super.prototype.serialize.call(this);
  34324. serializationObject.diameter = this.diameter;
  34325. serializationObject.thickness = this.thickness;
  34326. serializationObject.tessellation = this.tessellation;
  34327. return serializationObject;
  34328. };
  34329. TorusGeometry.Parse = function (parsedTorus, scene) {
  34330. if (scene.getGeometryByID(parsedTorus.id)) {
  34331. return null; // null since geometry could be something else than a torus...
  34332. }
  34333. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34334. if (BABYLON.Tags) {
  34335. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34336. }
  34337. scene.pushGeometry(torus, true);
  34338. return torus;
  34339. };
  34340. return TorusGeometry;
  34341. }(_PrimitiveGeometry));
  34342. BABYLON.TorusGeometry = TorusGeometry;
  34343. /**
  34344. * Creates a new ground geometry
  34345. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34346. */
  34347. var GroundGeometry = /** @class */ (function (_super) {
  34348. __extends(GroundGeometry, _super);
  34349. /**
  34350. * Creates a new ground geometry
  34351. * @param id defines the unique ID of the geometry
  34352. * @param scene defines the hosting scene
  34353. * @param width defines the width of the ground
  34354. * @param height defines the height of the ground
  34355. * @param subdivisions defines the subdivisions to apply to the ground
  34356. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34357. * @param mesh defines the hosting mesh (can be null)
  34358. */
  34359. function GroundGeometry(id, scene,
  34360. /**
  34361. * Defines the width of the ground
  34362. */
  34363. width,
  34364. /**
  34365. * Defines the height of the ground
  34366. */
  34367. height,
  34368. /**
  34369. * Defines the subdivisions to apply to the ground
  34370. */
  34371. subdivisions, canBeRegenerated, mesh) {
  34372. if (mesh === void 0) { mesh = null; }
  34373. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34374. _this.width = width;
  34375. _this.height = height;
  34376. _this.subdivisions = subdivisions;
  34377. return _this;
  34378. }
  34379. GroundGeometry.prototype._regenerateVertexData = function () {
  34380. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34381. };
  34382. GroundGeometry.prototype.copy = function (id) {
  34383. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34384. };
  34385. GroundGeometry.prototype.serialize = function () {
  34386. var serializationObject = _super.prototype.serialize.call(this);
  34387. serializationObject.width = this.width;
  34388. serializationObject.height = this.height;
  34389. serializationObject.subdivisions = this.subdivisions;
  34390. return serializationObject;
  34391. };
  34392. GroundGeometry.Parse = function (parsedGround, scene) {
  34393. if (scene.getGeometryByID(parsedGround.id)) {
  34394. return null; // null since geometry could be something else than a ground...
  34395. }
  34396. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34397. if (BABYLON.Tags) {
  34398. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34399. }
  34400. scene.pushGeometry(ground, true);
  34401. return ground;
  34402. };
  34403. return GroundGeometry;
  34404. }(_PrimitiveGeometry));
  34405. BABYLON.GroundGeometry = GroundGeometry;
  34406. /**
  34407. * Creates a tiled ground geometry
  34408. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34409. */
  34410. var TiledGroundGeometry = /** @class */ (function (_super) {
  34411. __extends(TiledGroundGeometry, _super);
  34412. /**
  34413. * Creates a tiled ground geometry
  34414. * @param id defines the unique ID of the geometry
  34415. * @param scene defines the hosting scene
  34416. * @param xmin defines the minimum value on X axis
  34417. * @param zmin defines the minimum value on Z axis
  34418. * @param xmax defines the maximum value on X axis
  34419. * @param zmax defines the maximum value on Z axis
  34420. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34421. * @param precision defines the precision to use when computing the tiles
  34422. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34423. * @param mesh defines the hosting mesh (can be null)
  34424. */
  34425. function TiledGroundGeometry(id, scene,
  34426. /**
  34427. * Defines the minimum value on X axis
  34428. */
  34429. xmin,
  34430. /**
  34431. * Defines the minimum value on Z axis
  34432. */
  34433. zmin,
  34434. /**
  34435. * Defines the maximum value on X axis
  34436. */
  34437. xmax,
  34438. /**
  34439. * Defines the maximum value on Z axis
  34440. */
  34441. zmax,
  34442. /**
  34443. * Defines the subdivisions to apply to the ground
  34444. */
  34445. subdivisions,
  34446. /**
  34447. * Defines the precision to use when computing the tiles
  34448. */
  34449. precision, canBeRegenerated, mesh) {
  34450. if (mesh === void 0) { mesh = null; }
  34451. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34452. _this.xmin = xmin;
  34453. _this.zmin = zmin;
  34454. _this.xmax = xmax;
  34455. _this.zmax = zmax;
  34456. _this.subdivisions = subdivisions;
  34457. _this.precision = precision;
  34458. return _this;
  34459. }
  34460. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34461. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34462. };
  34463. TiledGroundGeometry.prototype.copy = function (id) {
  34464. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34465. };
  34466. return TiledGroundGeometry;
  34467. }(_PrimitiveGeometry));
  34468. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34469. /**
  34470. * Creates a plane geometry
  34471. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34472. */
  34473. var PlaneGeometry = /** @class */ (function (_super) {
  34474. __extends(PlaneGeometry, _super);
  34475. /**
  34476. * Creates a plane geometry
  34477. * @param id defines the unique ID of the geometry
  34478. * @param scene defines the hosting scene
  34479. * @param size defines the size of the plane (width === height)
  34480. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34481. * @param mesh defines the hosting mesh (can be null)
  34482. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34483. */
  34484. function PlaneGeometry(id, scene,
  34485. /**
  34486. * Defines the size of the plane (width === height)
  34487. */
  34488. size, canBeRegenerated, mesh,
  34489. /**
  34490. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34491. */
  34492. side) {
  34493. if (mesh === void 0) { mesh = null; }
  34494. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34495. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34496. _this.size = size;
  34497. _this.side = side;
  34498. return _this;
  34499. }
  34500. PlaneGeometry.prototype._regenerateVertexData = function () {
  34501. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34502. };
  34503. PlaneGeometry.prototype.copy = function (id) {
  34504. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34505. };
  34506. PlaneGeometry.prototype.serialize = function () {
  34507. var serializationObject = _super.prototype.serialize.call(this);
  34508. serializationObject.size = this.size;
  34509. return serializationObject;
  34510. };
  34511. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34512. if (scene.getGeometryByID(parsedPlane.id)) {
  34513. return null; // null since geometry could be something else than a ground...
  34514. }
  34515. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34516. if (BABYLON.Tags) {
  34517. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34518. }
  34519. scene.pushGeometry(plane, true);
  34520. return plane;
  34521. };
  34522. return PlaneGeometry;
  34523. }(_PrimitiveGeometry));
  34524. BABYLON.PlaneGeometry = PlaneGeometry;
  34525. /**
  34526. * Creates a torus knot geometry
  34527. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34528. */
  34529. var TorusKnotGeometry = /** @class */ (function (_super) {
  34530. __extends(TorusKnotGeometry, _super);
  34531. /**
  34532. * Creates a torus knot geometry
  34533. * @param id defines the unique ID of the geometry
  34534. * @param scene defines the hosting scene
  34535. * @param radius defines the radius of the torus knot
  34536. * @param tube defines the thickness of the torus knot tube
  34537. * @param radialSegments defines the number of radial segments
  34538. * @param tubularSegments defines the number of tubular segments
  34539. * @param p defines the first number of windings
  34540. * @param q defines the second number of windings
  34541. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34542. * @param mesh defines the hosting mesh (can be null)
  34543. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34544. */
  34545. function TorusKnotGeometry(id, scene,
  34546. /**
  34547. * Defines the radius of the torus knot
  34548. */
  34549. radius,
  34550. /**
  34551. * Defines the thickness of the torus knot tube
  34552. */
  34553. tube,
  34554. /**
  34555. * Defines the number of radial segments
  34556. */
  34557. radialSegments,
  34558. /**
  34559. * Defines the number of tubular segments
  34560. */
  34561. tubularSegments,
  34562. /**
  34563. * Defines the first number of windings
  34564. */
  34565. p,
  34566. /**
  34567. * Defines the second number of windings
  34568. */
  34569. q, canBeRegenerated, mesh,
  34570. /**
  34571. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34572. */
  34573. side) {
  34574. if (mesh === void 0) { mesh = null; }
  34575. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34576. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34577. _this.radius = radius;
  34578. _this.tube = tube;
  34579. _this.radialSegments = radialSegments;
  34580. _this.tubularSegments = tubularSegments;
  34581. _this.p = p;
  34582. _this.q = q;
  34583. _this.side = side;
  34584. return _this;
  34585. }
  34586. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34587. 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 });
  34588. };
  34589. TorusKnotGeometry.prototype.copy = function (id) {
  34590. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34591. };
  34592. TorusKnotGeometry.prototype.serialize = function () {
  34593. var serializationObject = _super.prototype.serialize.call(this);
  34594. serializationObject.radius = this.radius;
  34595. serializationObject.tube = this.tube;
  34596. serializationObject.radialSegments = this.radialSegments;
  34597. serializationObject.tubularSegments = this.tubularSegments;
  34598. serializationObject.p = this.p;
  34599. serializationObject.q = this.q;
  34600. return serializationObject;
  34601. };
  34602. ;
  34603. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34604. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34605. return null; // null since geometry could be something else than a ground...
  34606. }
  34607. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34608. if (BABYLON.Tags) {
  34609. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34610. }
  34611. scene.pushGeometry(torusKnot, true);
  34612. return torusKnot;
  34613. };
  34614. return TorusKnotGeometry;
  34615. }(_PrimitiveGeometry));
  34616. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34617. //}
  34618. })(BABYLON || (BABYLON = {}));
  34619. //# sourceMappingURL=babylon.geometry.js.map
  34620. var BABYLON;
  34621. (function (BABYLON) {
  34622. /**
  34623. * PostProcessManager is used to manage one or more post processes or post process pipelines
  34624. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  34625. */
  34626. var PostProcessManager = /** @class */ (function () {
  34627. /**
  34628. * Creates a new instance of @see PostProcess
  34629. * @param scene The scene that the post process is associated with.
  34630. */
  34631. function PostProcessManager(scene) {
  34632. this._vertexBuffers = {};
  34633. this._scene = scene;
  34634. }
  34635. PostProcessManager.prototype._prepareBuffers = function () {
  34636. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34637. return;
  34638. }
  34639. // VBO
  34640. var vertices = [];
  34641. vertices.push(1, 1);
  34642. vertices.push(-1, 1);
  34643. vertices.push(-1, -1);
  34644. vertices.push(1, -1);
  34645. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34646. this._buildIndexBuffer();
  34647. };
  34648. PostProcessManager.prototype._buildIndexBuffer = function () {
  34649. // Indices
  34650. var indices = [];
  34651. indices.push(0);
  34652. indices.push(1);
  34653. indices.push(2);
  34654. indices.push(0);
  34655. indices.push(2);
  34656. indices.push(3);
  34657. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34658. };
  34659. /**
  34660. * Rebuilds the vertex buffers of the manager.
  34661. */
  34662. PostProcessManager.prototype._rebuild = function () {
  34663. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34664. if (!vb) {
  34665. return;
  34666. }
  34667. vb._rebuild();
  34668. this._buildIndexBuffer();
  34669. };
  34670. // Methods
  34671. /**
  34672. * Prepares a frame to be run through a post process.
  34673. * @param sourceTexture The input texture to the post procesess. (default: null)
  34674. * @param postProcesses An array of post processes to be run. (default: null)
  34675. * @returns True if the post processes were able to be run.
  34676. */
  34677. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34678. if (sourceTexture === void 0) { sourceTexture = null; }
  34679. if (postProcesses === void 0) { postProcesses = null; }
  34680. var camera = this._scene.activeCamera;
  34681. if (!camera) {
  34682. return false;
  34683. }
  34684. var postProcesses = postProcesses || camera._postProcesses;
  34685. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34686. return false;
  34687. }
  34688. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34689. return true;
  34690. };
  34691. /**
  34692. * Manually render a set of post processes to a texture.
  34693. * @param postProcesses An array of post processes to be run.
  34694. * @param targetTexture The target texture to render to.
  34695. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  34696. */
  34697. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34698. if (targetTexture === void 0) { targetTexture = null; }
  34699. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34700. var engine = this._scene.getEngine();
  34701. for (var index = 0; index < postProcesses.length; index++) {
  34702. if (index < postProcesses.length - 1) {
  34703. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34704. }
  34705. else {
  34706. if (targetTexture) {
  34707. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34708. }
  34709. else {
  34710. engine.restoreDefaultFramebuffer();
  34711. }
  34712. }
  34713. var pp = postProcesses[index];
  34714. var effect = pp.apply();
  34715. if (effect) {
  34716. pp.onBeforeRenderObservable.notifyObservers(effect);
  34717. // VBOs
  34718. this._prepareBuffers();
  34719. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34720. // Draw order
  34721. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34722. pp.onAfterRenderObservable.notifyObservers(effect);
  34723. }
  34724. }
  34725. // Restore depth buffer
  34726. engine.setDepthBuffer(true);
  34727. engine.setDepthWrite(true);
  34728. };
  34729. /**
  34730. * Finalize the result of the output of the postprocesses.
  34731. * @param doNotPresent If true the result will not be displayed to the screen.
  34732. * @param targetTexture The target texture to render to.
  34733. * @param faceIndex The index of the face to bind the target texture to.
  34734. * @param postProcesses The array of post processes to render.
  34735. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  34736. */
  34737. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34738. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34739. var camera = this._scene.activeCamera;
  34740. if (!camera) {
  34741. return;
  34742. }
  34743. postProcesses = postProcesses || camera._postProcesses;
  34744. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34745. return;
  34746. }
  34747. var engine = this._scene.getEngine();
  34748. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34749. if (index < len - 1) {
  34750. postProcesses[index + 1].activate(camera, targetTexture);
  34751. }
  34752. else {
  34753. if (targetTexture) {
  34754. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34755. }
  34756. else {
  34757. engine.restoreDefaultFramebuffer();
  34758. }
  34759. }
  34760. if (doNotPresent) {
  34761. break;
  34762. }
  34763. var pp = postProcesses[index];
  34764. var effect = pp.apply();
  34765. if (effect) {
  34766. pp.onBeforeRenderObservable.notifyObservers(effect);
  34767. // VBOs
  34768. this._prepareBuffers();
  34769. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34770. // Draw order
  34771. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34772. pp.onAfterRenderObservable.notifyObservers(effect);
  34773. }
  34774. }
  34775. // Restore states
  34776. engine.setDepthBuffer(true);
  34777. engine.setDepthWrite(true);
  34778. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34779. };
  34780. /**
  34781. * Disposes of the post process manager.
  34782. */
  34783. PostProcessManager.prototype.dispose = function () {
  34784. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34785. if (buffer) {
  34786. buffer.dispose();
  34787. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34788. }
  34789. if (this._indexBuffer) {
  34790. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34791. this._indexBuffer = null;
  34792. }
  34793. };
  34794. return PostProcessManager;
  34795. }());
  34796. BABYLON.PostProcessManager = PostProcessManager;
  34797. })(BABYLON || (BABYLON = {}));
  34798. //# sourceMappingURL=babylon.postProcessManager.js.map
  34799. var BABYLON;
  34800. (function (BABYLON) {
  34801. /**
  34802. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34803. */
  34804. var PerformanceMonitor = /** @class */ (function () {
  34805. /**
  34806. * constructor
  34807. * @param frameSampleSize The number of samples required to saturate the sliding window
  34808. */
  34809. function PerformanceMonitor(frameSampleSize) {
  34810. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34811. this._enabled = true;
  34812. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34813. }
  34814. /**
  34815. * Samples current frame
  34816. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34817. */
  34818. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34819. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34820. if (!this._enabled)
  34821. return;
  34822. if (this._lastFrameTimeMs != null) {
  34823. var dt = timeMs - this._lastFrameTimeMs;
  34824. this._rollingFrameTime.add(dt);
  34825. }
  34826. this._lastFrameTimeMs = timeMs;
  34827. };
  34828. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34829. /**
  34830. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34831. * @return Average frame time in milliseconds
  34832. */
  34833. get: function () {
  34834. return this._rollingFrameTime.average;
  34835. },
  34836. enumerable: true,
  34837. configurable: true
  34838. });
  34839. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34840. /**
  34841. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34842. * @return Frame time variance in milliseconds squared
  34843. */
  34844. get: function () {
  34845. return this._rollingFrameTime.variance;
  34846. },
  34847. enumerable: true,
  34848. configurable: true
  34849. });
  34850. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34851. /**
  34852. * Returns the frame time of the most recent frame
  34853. * @return Frame time in milliseconds
  34854. */
  34855. get: function () {
  34856. return this._rollingFrameTime.history(0);
  34857. },
  34858. enumerable: true,
  34859. configurable: true
  34860. });
  34861. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34862. /**
  34863. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34864. * @return Framerate in frames per second
  34865. */
  34866. get: function () {
  34867. return 1000.0 / this._rollingFrameTime.average;
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34873. /**
  34874. * Returns the average framerate in frames per second using the most recent frame time
  34875. * @return Framerate in frames per second
  34876. */
  34877. get: function () {
  34878. var history = this._rollingFrameTime.history(0);
  34879. if (history === 0) {
  34880. return 0;
  34881. }
  34882. return 1000.0 / history;
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34888. /**
  34889. * Returns true if enough samples have been taken to completely fill the sliding window
  34890. * @return true if saturated
  34891. */
  34892. get: function () {
  34893. return this._rollingFrameTime.isSaturated();
  34894. },
  34895. enumerable: true,
  34896. configurable: true
  34897. });
  34898. /**
  34899. * Enables contributions to the sliding window sample set
  34900. */
  34901. PerformanceMonitor.prototype.enable = function () {
  34902. this._enabled = true;
  34903. };
  34904. /**
  34905. * Disables contributions to the sliding window sample set
  34906. * Samples will not be interpolated over the disabled period
  34907. */
  34908. PerformanceMonitor.prototype.disable = function () {
  34909. this._enabled = false;
  34910. //clear last sample to avoid interpolating over the disabled period when next enabled
  34911. this._lastFrameTimeMs = null;
  34912. };
  34913. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34914. /**
  34915. * Returns true if sampling is enabled
  34916. * @return true if enabled
  34917. */
  34918. get: function () {
  34919. return this._enabled;
  34920. },
  34921. enumerable: true,
  34922. configurable: true
  34923. });
  34924. /**
  34925. * Resets performance monitor
  34926. */
  34927. PerformanceMonitor.prototype.reset = function () {
  34928. //clear last sample to avoid interpolating over the disabled period when next enabled
  34929. this._lastFrameTimeMs = null;
  34930. //wipe record
  34931. this._rollingFrameTime.reset();
  34932. };
  34933. return PerformanceMonitor;
  34934. }());
  34935. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34936. /**
  34937. * RollingAverage
  34938. *
  34939. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34940. */
  34941. var RollingAverage = /** @class */ (function () {
  34942. /**
  34943. * constructor
  34944. * @param length The number of samples required to saturate the sliding window
  34945. */
  34946. function RollingAverage(length) {
  34947. this._samples = new Array(length);
  34948. this.reset();
  34949. }
  34950. /**
  34951. * Adds a sample to the sample set
  34952. * @param v The sample value
  34953. */
  34954. RollingAverage.prototype.add = function (v) {
  34955. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34956. var delta;
  34957. //we need to check if we've already wrapped round
  34958. if (this.isSaturated()) {
  34959. //remove bottom of stack from mean
  34960. var bottomValue = this._samples[this._pos];
  34961. delta = bottomValue - this.average;
  34962. this.average -= delta / (this._sampleCount - 1);
  34963. this._m2 -= delta * (bottomValue - this.average);
  34964. }
  34965. else {
  34966. this._sampleCount++;
  34967. }
  34968. //add new value to mean
  34969. delta = v - this.average;
  34970. this.average += delta / (this._sampleCount);
  34971. this._m2 += delta * (v - this.average);
  34972. //set the new variance
  34973. this.variance = this._m2 / (this._sampleCount - 1);
  34974. this._samples[this._pos] = v;
  34975. this._pos++;
  34976. this._pos %= this._samples.length; //positive wrap around
  34977. };
  34978. /**
  34979. * Returns previously added values or null if outside of history or outside the sliding window domain
  34980. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34981. * @return Value previously recorded with add() or null if outside of range
  34982. */
  34983. RollingAverage.prototype.history = function (i) {
  34984. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34985. return 0;
  34986. }
  34987. var i0 = this._wrapPosition(this._pos - 1.0);
  34988. return this._samples[this._wrapPosition(i0 - i)];
  34989. };
  34990. /**
  34991. * Returns true if enough samples have been taken to completely fill the sliding window
  34992. * @return true if sample-set saturated
  34993. */
  34994. RollingAverage.prototype.isSaturated = function () {
  34995. return this._sampleCount >= this._samples.length;
  34996. };
  34997. /**
  34998. * Resets the rolling average (equivalent to 0 samples taken so far)
  34999. */
  35000. RollingAverage.prototype.reset = function () {
  35001. this.average = 0;
  35002. this.variance = 0;
  35003. this._sampleCount = 0;
  35004. this._pos = 0;
  35005. this._m2 = 0;
  35006. };
  35007. /**
  35008. * Wraps a value around the sample range boundaries
  35009. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  35010. * @return Wrapped position in sample range
  35011. */
  35012. RollingAverage.prototype._wrapPosition = function (i) {
  35013. var max = this._samples.length;
  35014. return ((i % max) + max) % max;
  35015. };
  35016. return RollingAverage;
  35017. }());
  35018. BABYLON.RollingAverage = RollingAverage;
  35019. })(BABYLON || (BABYLON = {}));
  35020. //# sourceMappingURL=babylon.performanceMonitor.js.map
  35021. var BABYLON;
  35022. (function (BABYLON) {
  35023. /**
  35024. * This groups together the common properties used for image processing either in direct forward pass
  35025. * or through post processing effect depending on the use of the image processing pipeline in your scene
  35026. * or not.
  35027. */
  35028. var ImageProcessingConfiguration = /** @class */ (function () {
  35029. function ImageProcessingConfiguration() {
  35030. /**
  35031. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  35032. */
  35033. this.colorCurves = new BABYLON.ColorCurves();
  35034. this._colorCurvesEnabled = false;
  35035. this._colorGradingEnabled = false;
  35036. this._colorGradingWithGreenDepth = true;
  35037. this._colorGradingBGR = true;
  35038. this._exposure = 1.0;
  35039. this._toneMappingEnabled = false;
  35040. this._contrast = 1.0;
  35041. /**
  35042. * Vignette stretch size.
  35043. */
  35044. this.vignetteStretch = 0;
  35045. /**
  35046. * Vignette centre X Offset.
  35047. */
  35048. this.vignetteCentreX = 0;
  35049. /**
  35050. * Vignette centre Y Offset.
  35051. */
  35052. this.vignetteCentreY = 0;
  35053. /**
  35054. * Vignette weight or intensity of the vignette effect.
  35055. */
  35056. this.vignetteWeight = 1.5;
  35057. /**
  35058. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  35059. * if vignetteEnabled is set to true.
  35060. */
  35061. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  35062. /**
  35063. * Camera field of view used by the Vignette effect.
  35064. */
  35065. this.vignetteCameraFov = 0.5;
  35066. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  35067. this._vignetteEnabled = false;
  35068. this._applyByPostProcess = false;
  35069. this._isEnabled = true;
  35070. /**
  35071. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  35072. * @type {BABYLON.Observable}
  35073. */
  35074. this.onUpdateParameters = new BABYLON.Observable();
  35075. }
  35076. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  35077. /**
  35078. * Gets wether the color curves effect is enabled.
  35079. */
  35080. get: function () {
  35081. return this._colorCurvesEnabled;
  35082. },
  35083. /**
  35084. * Sets wether the color curves effect is enabled.
  35085. */
  35086. set: function (value) {
  35087. if (this._colorCurvesEnabled === value) {
  35088. return;
  35089. }
  35090. this._colorCurvesEnabled = value;
  35091. this._updateParameters();
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  35097. /**
  35098. * Gets wether the color grading effect is enabled.
  35099. */
  35100. get: function () {
  35101. return this._colorGradingEnabled;
  35102. },
  35103. /**
  35104. * Sets wether the color grading effect is enabled.
  35105. */
  35106. set: function (value) {
  35107. if (this._colorGradingEnabled === value) {
  35108. return;
  35109. }
  35110. this._colorGradingEnabled = value;
  35111. this._updateParameters();
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  35117. /**
  35118. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  35119. */
  35120. get: function () {
  35121. return this._colorGradingWithGreenDepth;
  35122. },
  35123. /**
  35124. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  35125. */
  35126. set: function (value) {
  35127. if (this._colorGradingWithGreenDepth === value) {
  35128. return;
  35129. }
  35130. this._colorGradingWithGreenDepth = value;
  35131. this._updateParameters();
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  35137. /**
  35138. * Gets wether the color grading texture contains BGR values.
  35139. */
  35140. get: function () {
  35141. return this._colorGradingBGR;
  35142. },
  35143. /**
  35144. * Sets wether the color grading texture contains BGR values.
  35145. */
  35146. set: function (value) {
  35147. if (this._colorGradingBGR === value) {
  35148. return;
  35149. }
  35150. this._colorGradingBGR = value;
  35151. this._updateParameters();
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  35157. /**
  35158. * Gets the Exposure used in the effect.
  35159. */
  35160. get: function () {
  35161. return this._exposure;
  35162. },
  35163. /**
  35164. * Sets the Exposure used in the effect.
  35165. */
  35166. set: function (value) {
  35167. if (this._exposure === value) {
  35168. return;
  35169. }
  35170. this._exposure = value;
  35171. this._updateParameters();
  35172. },
  35173. enumerable: true,
  35174. configurable: true
  35175. });
  35176. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  35177. /**
  35178. * Gets wether the tone mapping effect is enabled.
  35179. */
  35180. get: function () {
  35181. return this._toneMappingEnabled;
  35182. },
  35183. /**
  35184. * Sets wether the tone mapping effect is enabled.
  35185. */
  35186. set: function (value) {
  35187. if (this._toneMappingEnabled === value) {
  35188. return;
  35189. }
  35190. this._toneMappingEnabled = value;
  35191. this._updateParameters();
  35192. },
  35193. enumerable: true,
  35194. configurable: true
  35195. });
  35196. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  35197. /**
  35198. * Gets the contrast used in the effect.
  35199. */
  35200. get: function () {
  35201. return this._contrast;
  35202. },
  35203. /**
  35204. * Sets the contrast used in the effect.
  35205. */
  35206. set: function (value) {
  35207. if (this._contrast === value) {
  35208. return;
  35209. }
  35210. this._contrast = value;
  35211. this._updateParameters();
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  35217. /**
  35218. * Gets the vignette blend mode allowing different kind of effect.
  35219. */
  35220. get: function () {
  35221. return this._vignetteBlendMode;
  35222. },
  35223. /**
  35224. * Sets the vignette blend mode allowing different kind of effect.
  35225. */
  35226. set: function (value) {
  35227. if (this._vignetteBlendMode === value) {
  35228. return;
  35229. }
  35230. this._vignetteBlendMode = value;
  35231. this._updateParameters();
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  35237. /**
  35238. * Gets wether the vignette effect is enabled.
  35239. */
  35240. get: function () {
  35241. return this._vignetteEnabled;
  35242. },
  35243. /**
  35244. * Sets wether the vignette effect is enabled.
  35245. */
  35246. set: function (value) {
  35247. if (this._vignetteEnabled === value) {
  35248. return;
  35249. }
  35250. this._vignetteEnabled = value;
  35251. this._updateParameters();
  35252. },
  35253. enumerable: true,
  35254. configurable: true
  35255. });
  35256. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  35257. /**
  35258. * Gets wether the image processing is applied through a post process or not.
  35259. */
  35260. get: function () {
  35261. return this._applyByPostProcess;
  35262. },
  35263. /**
  35264. * Sets wether the image processing is applied through a post process or not.
  35265. */
  35266. set: function (value) {
  35267. if (this._applyByPostProcess === value) {
  35268. return;
  35269. }
  35270. this._applyByPostProcess = value;
  35271. this._updateParameters();
  35272. },
  35273. enumerable: true,
  35274. configurable: true
  35275. });
  35276. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  35277. /**
  35278. * Gets wether the image processing is enabled or not.
  35279. */
  35280. get: function () {
  35281. return this._isEnabled;
  35282. },
  35283. /**
  35284. * Sets wether the image processing is enabled or not.
  35285. */
  35286. set: function (value) {
  35287. if (this._isEnabled === value) {
  35288. return;
  35289. }
  35290. this._isEnabled = value;
  35291. this._updateParameters();
  35292. },
  35293. enumerable: true,
  35294. configurable: true
  35295. });
  35296. /**
  35297. * Method called each time the image processing information changes requires to recompile the effect.
  35298. */
  35299. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35300. this.onUpdateParameters.notifyObservers(this);
  35301. };
  35302. ImageProcessingConfiguration.prototype.getClassName = function () {
  35303. return "ImageProcessingConfiguration";
  35304. };
  35305. /**
  35306. * Prepare the list of uniforms associated with the Image Processing effects.
  35307. * @param uniformsList The list of uniforms used in the effect
  35308. * @param defines the list of defines currently in use
  35309. */
  35310. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35311. if (defines.EXPOSURE) {
  35312. uniforms.push("exposureLinear");
  35313. }
  35314. if (defines.CONTRAST) {
  35315. uniforms.push("contrast");
  35316. }
  35317. if (defines.COLORGRADING) {
  35318. uniforms.push("colorTransformSettings");
  35319. }
  35320. if (defines.VIGNETTE) {
  35321. uniforms.push("vInverseScreenSize");
  35322. uniforms.push("vignetteSettings1");
  35323. uniforms.push("vignetteSettings2");
  35324. }
  35325. if (defines.COLORCURVES) {
  35326. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35327. }
  35328. };
  35329. /**
  35330. * Prepare the list of samplers associated with the Image Processing effects.
  35331. * @param uniformsList The list of uniforms used in the effect
  35332. * @param defines the list of defines currently in use
  35333. */
  35334. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35335. if (defines.COLORGRADING) {
  35336. samplersList.push("txColorTransform");
  35337. }
  35338. };
  35339. /**
  35340. * Prepare the list of defines associated to the shader.
  35341. * @param defines the list of defines to complete
  35342. */
  35343. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35344. if (forPostProcess === void 0) { forPostProcess = false; }
  35345. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35346. defines.VIGNETTE = false;
  35347. defines.TONEMAPPING = false;
  35348. defines.CONTRAST = false;
  35349. defines.EXPOSURE = false;
  35350. defines.COLORCURVES = false;
  35351. defines.COLORGRADING = false;
  35352. defines.COLORGRADING3D = false;
  35353. defines.IMAGEPROCESSING = false;
  35354. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35355. return;
  35356. }
  35357. defines.VIGNETTE = this.vignetteEnabled;
  35358. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35359. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35360. defines.TONEMAPPING = this.toneMappingEnabled;
  35361. defines.CONTRAST = (this.contrast !== 1.0);
  35362. defines.EXPOSURE = (this.exposure !== 1.0);
  35363. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35364. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35365. if (defines.COLORGRADING) {
  35366. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35367. }
  35368. else {
  35369. defines.COLORGRADING3D = false;
  35370. }
  35371. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35372. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35373. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35374. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35375. };
  35376. /**
  35377. * Returns true if all the image processing information are ready.
  35378. */
  35379. ImageProcessingConfiguration.prototype.isReady = function () {
  35380. // Color Grading texure can not be none blocking.
  35381. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35382. };
  35383. /**
  35384. * Binds the image processing to the shader.
  35385. * @param effect The effect to bind to
  35386. */
  35387. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35388. if (aspectRatio === void 0) { aspectRatio = 1; }
  35389. // Color Curves
  35390. if (this._colorCurvesEnabled && this.colorCurves) {
  35391. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35392. }
  35393. // Vignette
  35394. if (this._vignetteEnabled) {
  35395. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35396. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35397. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35398. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35399. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35400. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35401. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35402. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35403. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35404. var vignettePower = -2.0 * this.vignetteWeight;
  35405. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35406. }
  35407. // Exposure
  35408. effect.setFloat("exposureLinear", this.exposure);
  35409. // Contrast
  35410. effect.setFloat("contrast", this.contrast);
  35411. // Color transform settings
  35412. if (this.colorGradingTexture) {
  35413. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35414. var textureSize = this.colorGradingTexture.getSize().height;
  35415. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35416. 0.5 / textureSize, // textureOffset
  35417. textureSize, // textureSize
  35418. this.colorGradingTexture.level // weight
  35419. );
  35420. }
  35421. };
  35422. /**
  35423. * Clones the current image processing instance.
  35424. * @return The cloned image processing
  35425. */
  35426. ImageProcessingConfiguration.prototype.clone = function () {
  35427. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35428. };
  35429. /**
  35430. * Serializes the current image processing instance to a json representation.
  35431. * @return a JSON representation
  35432. */
  35433. ImageProcessingConfiguration.prototype.serialize = function () {
  35434. return BABYLON.SerializationHelper.Serialize(this);
  35435. };
  35436. /**
  35437. * Parses the image processing from a json representation.
  35438. * @param source the JSON source to parse
  35439. * @return The parsed image processing
  35440. */
  35441. ImageProcessingConfiguration.Parse = function (source) {
  35442. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35443. };
  35444. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35445. /**
  35446. * Used to apply the vignette as a mix with the pixel color.
  35447. */
  35448. get: function () {
  35449. return this._VIGNETTEMODE_MULTIPLY;
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35455. /**
  35456. * Used to apply the vignette as a replacement of the pixel color.
  35457. */
  35458. get: function () {
  35459. return this._VIGNETTEMODE_OPAQUE;
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. // Static constants associated to the image processing.
  35465. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35466. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35467. __decorate([
  35468. BABYLON.serializeAsColorCurves()
  35469. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35470. __decorate([
  35471. BABYLON.serialize()
  35472. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35473. __decorate([
  35474. BABYLON.serializeAsTexture()
  35475. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35476. __decorate([
  35477. BABYLON.serialize()
  35478. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35479. __decorate([
  35480. BABYLON.serialize()
  35481. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35482. __decorate([
  35483. BABYLON.serialize()
  35484. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35485. __decorate([
  35486. BABYLON.serialize()
  35487. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35488. __decorate([
  35489. BABYLON.serialize()
  35490. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35491. __decorate([
  35492. BABYLON.serialize()
  35493. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35494. __decorate([
  35495. BABYLON.serialize()
  35496. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35497. __decorate([
  35498. BABYLON.serialize()
  35499. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35500. __decorate([
  35501. BABYLON.serialize()
  35502. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35503. __decorate([
  35504. BABYLON.serialize()
  35505. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35506. __decorate([
  35507. BABYLON.serializeAsColor4()
  35508. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35509. __decorate([
  35510. BABYLON.serialize()
  35511. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35512. __decorate([
  35513. BABYLON.serialize()
  35514. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35515. __decorate([
  35516. BABYLON.serialize()
  35517. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35518. __decorate([
  35519. BABYLON.serialize()
  35520. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35521. __decorate([
  35522. BABYLON.serialize()
  35523. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35524. return ImageProcessingConfiguration;
  35525. }());
  35526. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35527. })(BABYLON || (BABYLON = {}));
  35528. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35529. var BABYLON;
  35530. (function (BABYLON) {
  35531. /**
  35532. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35533. * It can help converting any input color in a desired output one. This can then be used to create effects
  35534. * from sepia, black and white to sixties or futuristic rendering...
  35535. *
  35536. * The only supported format is currently 3dl.
  35537. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35538. */
  35539. var ColorGradingTexture = /** @class */ (function (_super) {
  35540. __extends(ColorGradingTexture, _super);
  35541. /**
  35542. * Instantiates a ColorGradingTexture from the following parameters.
  35543. *
  35544. * @param url The location of the color gradind data (currently only supporting 3dl)
  35545. * @param scene The scene the texture will be used in
  35546. */
  35547. function ColorGradingTexture(url, scene) {
  35548. var _this = _super.call(this, scene) || this;
  35549. if (!url) {
  35550. return _this;
  35551. }
  35552. _this._engine = scene.getEngine();
  35553. _this._textureMatrix = BABYLON.Matrix.Identity();
  35554. _this.name = url;
  35555. _this.url = url;
  35556. _this.hasAlpha = false;
  35557. _this.isCube = false;
  35558. _this.is3D = _this._engine.webGLVersion > 1;
  35559. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35560. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35561. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35562. _this.anisotropicFilteringLevel = 1;
  35563. _this._texture = _this._getFromCache(url, true);
  35564. if (!_this._texture) {
  35565. if (!scene.useDelayedTextureLoading) {
  35566. _this.loadTexture();
  35567. }
  35568. else {
  35569. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35570. }
  35571. }
  35572. return _this;
  35573. }
  35574. /**
  35575. * Returns the texture matrix used in most of the material.
  35576. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35577. */
  35578. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35579. return this._textureMatrix;
  35580. };
  35581. /**
  35582. * Occurs when the file being loaded is a .3dl LUT file.
  35583. */
  35584. ColorGradingTexture.prototype.load3dlTexture = function () {
  35585. var engine = this._engine;
  35586. var texture;
  35587. if (engine.webGLVersion === 1) {
  35588. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35589. }
  35590. else {
  35591. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35592. }
  35593. this._texture = texture;
  35594. var callback = function (text) {
  35595. if (typeof text !== "string") {
  35596. return;
  35597. }
  35598. var data = null;
  35599. var tempData = null;
  35600. var line;
  35601. var lines = text.split('\n');
  35602. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35603. var maxColor = 0;
  35604. for (var i = 0; i < lines.length; i++) {
  35605. line = lines[i];
  35606. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35607. continue;
  35608. if (line.indexOf('#') === 0)
  35609. continue;
  35610. var words = line.split(" ");
  35611. if (size === 0) {
  35612. // Number of space + one
  35613. size = words.length;
  35614. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35615. tempData = new Float32Array(size * size * size * 4);
  35616. continue;
  35617. }
  35618. if (size != 0) {
  35619. var r = Math.max(parseInt(words[0]), 0);
  35620. var g = Math.max(parseInt(words[1]), 0);
  35621. var b = Math.max(parseInt(words[2]), 0);
  35622. maxColor = Math.max(r, maxColor);
  35623. maxColor = Math.max(g, maxColor);
  35624. maxColor = Math.max(b, maxColor);
  35625. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35626. if (tempData) {
  35627. tempData[pixelStorageIndex + 0] = r;
  35628. tempData[pixelStorageIndex + 1] = g;
  35629. tempData[pixelStorageIndex + 2] = b;
  35630. }
  35631. pixelIndexSlice++;
  35632. if (pixelIndexSlice % size == 0) {
  35633. pixelIndexH++;
  35634. pixelIndexSlice = 0;
  35635. if (pixelIndexH % size == 0) {
  35636. pixelIndexW++;
  35637. pixelIndexH = 0;
  35638. }
  35639. }
  35640. }
  35641. }
  35642. if (tempData && data) {
  35643. for (var i = 0; i < tempData.length; i++) {
  35644. if (i > 0 && (i + 1) % 4 === 0) {
  35645. data[i] = 255;
  35646. }
  35647. else {
  35648. var value = tempData[i];
  35649. data[i] = (value / maxColor * 255);
  35650. }
  35651. }
  35652. }
  35653. if (texture.is3D) {
  35654. texture.updateSize(size, size, size);
  35655. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35656. }
  35657. else {
  35658. texture.updateSize(size * size, size);
  35659. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35660. }
  35661. };
  35662. var scene = this.getScene();
  35663. if (scene) {
  35664. scene._loadFile(this.url, callback);
  35665. }
  35666. else {
  35667. this._engine._loadFile(this.url, callback);
  35668. }
  35669. return this._texture;
  35670. };
  35671. /**
  35672. * Starts the loading process of the texture.
  35673. */
  35674. ColorGradingTexture.prototype.loadTexture = function () {
  35675. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35676. this.load3dlTexture();
  35677. }
  35678. };
  35679. /**
  35680. * Clones the color gradind texture.
  35681. */
  35682. ColorGradingTexture.prototype.clone = function () {
  35683. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35684. // Base texture
  35685. newTexture.level = this.level;
  35686. return newTexture;
  35687. };
  35688. /**
  35689. * Called during delayed load for textures.
  35690. */
  35691. ColorGradingTexture.prototype.delayLoad = function () {
  35692. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35693. return;
  35694. }
  35695. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35696. this._texture = this._getFromCache(this.url, true);
  35697. if (!this._texture) {
  35698. this.loadTexture();
  35699. }
  35700. };
  35701. /**
  35702. * Parses a color grading texture serialized by Babylon.
  35703. * @param parsedTexture The texture information being parsedTexture
  35704. * @param scene The scene to load the texture in
  35705. * @param rootUrl The root url of the data assets to load
  35706. * @return A color gradind texture
  35707. */
  35708. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35709. var texture = null;
  35710. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35711. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35712. texture.name = parsedTexture.name;
  35713. texture.level = parsedTexture.level;
  35714. }
  35715. return texture;
  35716. };
  35717. /**
  35718. * Serializes the LUT texture to json format.
  35719. */
  35720. ColorGradingTexture.prototype.serialize = function () {
  35721. if (!this.name) {
  35722. return null;
  35723. }
  35724. var serializationObject = {};
  35725. serializationObject.name = this.name;
  35726. serializationObject.level = this.level;
  35727. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35728. return serializationObject;
  35729. };
  35730. /**
  35731. * Empty line regex stored for GC.
  35732. */
  35733. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35734. return ColorGradingTexture;
  35735. }(BABYLON.BaseTexture));
  35736. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35737. })(BABYLON || (BABYLON = {}));
  35738. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35739. var BABYLON;
  35740. (function (BABYLON) {
  35741. /**
  35742. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35743. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35744. * 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;
  35745. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35746. */
  35747. var ColorCurves = /** @class */ (function () {
  35748. function ColorCurves() {
  35749. this._dirty = true;
  35750. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35751. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35752. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35753. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35754. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35755. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35756. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35757. this._globalHue = 30;
  35758. this._globalDensity = 0;
  35759. this._globalSaturation = 0;
  35760. this._globalExposure = 0;
  35761. this._highlightsHue = 30;
  35762. this._highlightsDensity = 0;
  35763. this._highlightsSaturation = 0;
  35764. this._highlightsExposure = 0;
  35765. this._midtonesHue = 30;
  35766. this._midtonesDensity = 0;
  35767. this._midtonesSaturation = 0;
  35768. this._midtonesExposure = 0;
  35769. this._shadowsHue = 30;
  35770. this._shadowsDensity = 0;
  35771. this._shadowsSaturation = 0;
  35772. this._shadowsExposure = 0;
  35773. }
  35774. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35775. /**
  35776. * Gets the global Hue value.
  35777. * 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).
  35778. */
  35779. get: function () {
  35780. return this._globalHue;
  35781. },
  35782. /**
  35783. * Sets the global Hue value.
  35784. * 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).
  35785. */
  35786. set: function (value) {
  35787. this._globalHue = value;
  35788. this._dirty = true;
  35789. },
  35790. enumerable: true,
  35791. configurable: true
  35792. });
  35793. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35794. /**
  35795. * Gets the global Density value.
  35796. * 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.
  35797. * Values less than zero provide a filter of opposite hue.
  35798. */
  35799. get: function () {
  35800. return this._globalDensity;
  35801. },
  35802. /**
  35803. * Sets the global Density value.
  35804. * 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.
  35805. * Values less than zero provide a filter of opposite hue.
  35806. */
  35807. set: function (value) {
  35808. this._globalDensity = value;
  35809. this._dirty = true;
  35810. },
  35811. enumerable: true,
  35812. configurable: true
  35813. });
  35814. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35815. /**
  35816. * Gets the global Saturation value.
  35817. * 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.
  35818. */
  35819. get: function () {
  35820. return this._globalSaturation;
  35821. },
  35822. /**
  35823. * Sets the global Saturation value.
  35824. * 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.
  35825. */
  35826. set: function (value) {
  35827. this._globalSaturation = value;
  35828. this._dirty = true;
  35829. },
  35830. enumerable: true,
  35831. configurable: true
  35832. });
  35833. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35834. /**
  35835. * Gets the highlights Hue value.
  35836. * 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).
  35837. */
  35838. get: function () {
  35839. return this._highlightsHue;
  35840. },
  35841. /**
  35842. * Sets the highlights Hue value.
  35843. * 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).
  35844. */
  35845. set: function (value) {
  35846. this._highlightsHue = value;
  35847. this._dirty = true;
  35848. },
  35849. enumerable: true,
  35850. configurable: true
  35851. });
  35852. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35853. /**
  35854. * Gets the highlights Density value.
  35855. * 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.
  35856. * Values less than zero provide a filter of opposite hue.
  35857. */
  35858. get: function () {
  35859. return this._highlightsDensity;
  35860. },
  35861. /**
  35862. * Sets the highlights Density value.
  35863. * 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.
  35864. * Values less than zero provide a filter of opposite hue.
  35865. */
  35866. set: function (value) {
  35867. this._highlightsDensity = value;
  35868. this._dirty = true;
  35869. },
  35870. enumerable: true,
  35871. configurable: true
  35872. });
  35873. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35874. /**
  35875. * Gets the highlights Saturation value.
  35876. * 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.
  35877. */
  35878. get: function () {
  35879. return this._highlightsSaturation;
  35880. },
  35881. /**
  35882. * Sets the highlights Saturation value.
  35883. * 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.
  35884. */
  35885. set: function (value) {
  35886. this._highlightsSaturation = value;
  35887. this._dirty = true;
  35888. },
  35889. enumerable: true,
  35890. configurable: true
  35891. });
  35892. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35893. /**
  35894. * Gets the highlights Exposure value.
  35895. * 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.
  35896. */
  35897. get: function () {
  35898. return this._highlightsExposure;
  35899. },
  35900. /**
  35901. * Sets the highlights Exposure value.
  35902. * 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.
  35903. */
  35904. set: function (value) {
  35905. this._highlightsExposure = value;
  35906. this._dirty = true;
  35907. },
  35908. enumerable: true,
  35909. configurable: true
  35910. });
  35911. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35912. /**
  35913. * Gets the midtones Hue value.
  35914. * 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).
  35915. */
  35916. get: function () {
  35917. return this._midtonesHue;
  35918. },
  35919. /**
  35920. * Sets the midtones Hue value.
  35921. * 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).
  35922. */
  35923. set: function (value) {
  35924. this._midtonesHue = value;
  35925. this._dirty = true;
  35926. },
  35927. enumerable: true,
  35928. configurable: true
  35929. });
  35930. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35931. /**
  35932. * Gets the midtones Density value.
  35933. * 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.
  35934. * Values less than zero provide a filter of opposite hue.
  35935. */
  35936. get: function () {
  35937. return this._midtonesDensity;
  35938. },
  35939. /**
  35940. * Sets the midtones Density value.
  35941. * 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.
  35942. * Values less than zero provide a filter of opposite hue.
  35943. */
  35944. set: function (value) {
  35945. this._midtonesDensity = value;
  35946. this._dirty = true;
  35947. },
  35948. enumerable: true,
  35949. configurable: true
  35950. });
  35951. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35952. /**
  35953. * Gets the midtones Saturation value.
  35954. * 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.
  35955. */
  35956. get: function () {
  35957. return this._midtonesSaturation;
  35958. },
  35959. /**
  35960. * Sets the midtones Saturation value.
  35961. * 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.
  35962. */
  35963. set: function (value) {
  35964. this._midtonesSaturation = value;
  35965. this._dirty = true;
  35966. },
  35967. enumerable: true,
  35968. configurable: true
  35969. });
  35970. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35971. /**
  35972. * Gets the midtones Exposure value.
  35973. * 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.
  35974. */
  35975. get: function () {
  35976. return this._midtonesExposure;
  35977. },
  35978. /**
  35979. * Sets the midtones Exposure value.
  35980. * 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.
  35981. */
  35982. set: function (value) {
  35983. this._midtonesExposure = value;
  35984. this._dirty = true;
  35985. },
  35986. enumerable: true,
  35987. configurable: true
  35988. });
  35989. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35990. /**
  35991. * Gets the shadows Hue value.
  35992. * 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).
  35993. */
  35994. get: function () {
  35995. return this._shadowsHue;
  35996. },
  35997. /**
  35998. * Sets the shadows Hue value.
  35999. * 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).
  36000. */
  36001. set: function (value) {
  36002. this._shadowsHue = value;
  36003. this._dirty = true;
  36004. },
  36005. enumerable: true,
  36006. configurable: true
  36007. });
  36008. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  36009. /**
  36010. * Gets the shadows Density value.
  36011. * 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.
  36012. * Values less than zero provide a filter of opposite hue.
  36013. */
  36014. get: function () {
  36015. return this._shadowsDensity;
  36016. },
  36017. /**
  36018. * Sets the shadows Density value.
  36019. * 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.
  36020. * Values less than zero provide a filter of opposite hue.
  36021. */
  36022. set: function (value) {
  36023. this._shadowsDensity = value;
  36024. this._dirty = true;
  36025. },
  36026. enumerable: true,
  36027. configurable: true
  36028. });
  36029. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  36030. /**
  36031. * Gets the shadows Saturation value.
  36032. * 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.
  36033. */
  36034. get: function () {
  36035. return this._shadowsSaturation;
  36036. },
  36037. /**
  36038. * Sets the shadows Saturation value.
  36039. * 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.
  36040. */
  36041. set: function (value) {
  36042. this._shadowsSaturation = value;
  36043. this._dirty = true;
  36044. },
  36045. enumerable: true,
  36046. configurable: true
  36047. });
  36048. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  36049. /**
  36050. * Gets the shadows Exposure value.
  36051. * 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.
  36052. */
  36053. get: function () {
  36054. return this._shadowsExposure;
  36055. },
  36056. /**
  36057. * Sets the shadows Exposure value.
  36058. * 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.
  36059. */
  36060. set: function (value) {
  36061. this._shadowsExposure = value;
  36062. this._dirty = true;
  36063. },
  36064. enumerable: true,
  36065. configurable: true
  36066. });
  36067. ColorCurves.prototype.getClassName = function () {
  36068. return "ColorCurves";
  36069. };
  36070. /**
  36071. * Binds the color curves to the shader.
  36072. * @param colorCurves The color curve to bind
  36073. * @param effect The effect to bind to
  36074. */
  36075. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  36076. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  36077. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  36078. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  36079. if (colorCurves._dirty) {
  36080. colorCurves._dirty = false;
  36081. // Fill in global info.
  36082. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  36083. // Compute highlights info.
  36084. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  36085. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  36086. // Compute midtones info.
  36087. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  36088. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  36089. // Compute shadows info.
  36090. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  36091. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  36092. // Compute deltas (neutral is midtones).
  36093. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  36094. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  36095. }
  36096. if (effect) {
  36097. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  36098. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  36099. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  36100. }
  36101. };
  36102. /**
  36103. * Prepare the list of uniforms associated with the ColorCurves effects.
  36104. * @param uniformsList The list of uniforms used in the effect
  36105. */
  36106. ColorCurves.PrepareUniforms = function (uniformsList) {
  36107. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  36108. };
  36109. /**
  36110. * Returns color grading data based on a hue, density, saturation and exposure value.
  36111. * @param filterHue The hue of the color filter.
  36112. * @param filterDensity The density of the color filter.
  36113. * @param saturation The saturation.
  36114. * @param exposure The exposure.
  36115. * @param result The result data container.
  36116. */
  36117. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  36118. if (hue == null) {
  36119. return;
  36120. }
  36121. hue = ColorCurves.clamp(hue, 0, 360);
  36122. density = ColorCurves.clamp(density, -100, 100);
  36123. saturation = ColorCurves.clamp(saturation, -100, 100);
  36124. exposure = ColorCurves.clamp(exposure, -100, 100);
  36125. // Remap the slider/config filter density with non-linear mapping and also scale by half
  36126. // so that the maximum filter density is only 50% control. This provides fine control
  36127. // for small values and reasonable range.
  36128. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  36129. density *= 0.5;
  36130. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  36131. if (density < 0) {
  36132. density *= -1;
  36133. hue = (hue + 180) % 360;
  36134. }
  36135. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  36136. result.scaleToRef(2, result);
  36137. result.a = 1 + 0.01 * saturation;
  36138. };
  36139. /**
  36140. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  36141. * @param value The input slider value in range [-100,100].
  36142. * @returns Adjusted value.
  36143. */
  36144. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  36145. value /= 100;
  36146. var x = Math.abs(value);
  36147. x = Math.pow(x, 2);
  36148. if (value < 0) {
  36149. x *= -1;
  36150. }
  36151. x *= 100;
  36152. return x;
  36153. };
  36154. /**
  36155. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  36156. * @param hue The hue (H) input.
  36157. * @param saturation The saturation (S) input.
  36158. * @param brightness The brightness (B) input.
  36159. * @result An RGBA color represented as Vector4.
  36160. */
  36161. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  36162. var h = ColorCurves.clamp(hue, 0, 360);
  36163. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  36164. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  36165. if (s === 0) {
  36166. result.r = v;
  36167. result.g = v;
  36168. result.b = v;
  36169. }
  36170. else {
  36171. // sector 0 to 5
  36172. h /= 60;
  36173. var i = Math.floor(h);
  36174. // fractional part of h
  36175. var f = h - i;
  36176. var p = v * (1 - s);
  36177. var q = v * (1 - s * f);
  36178. var t = v * (1 - s * (1 - f));
  36179. switch (i) {
  36180. case 0:
  36181. result.r = v;
  36182. result.g = t;
  36183. result.b = p;
  36184. break;
  36185. case 1:
  36186. result.r = q;
  36187. result.g = v;
  36188. result.b = p;
  36189. break;
  36190. case 2:
  36191. result.r = p;
  36192. result.g = v;
  36193. result.b = t;
  36194. break;
  36195. case 3:
  36196. result.r = p;
  36197. result.g = q;
  36198. result.b = v;
  36199. break;
  36200. case 4:
  36201. result.r = t;
  36202. result.g = p;
  36203. result.b = v;
  36204. break;
  36205. default:// case 5:
  36206. result.r = v;
  36207. result.g = p;
  36208. result.b = q;
  36209. break;
  36210. }
  36211. }
  36212. result.a = 1;
  36213. };
  36214. /**
  36215. * Returns a value clamped between min and max
  36216. * @param value The value to clamp
  36217. * @param min The minimum of value
  36218. * @param max The maximum of value
  36219. * @returns The clamped value.
  36220. */
  36221. ColorCurves.clamp = function (value, min, max) {
  36222. return Math.min(Math.max(value, min), max);
  36223. };
  36224. /**
  36225. * Clones the current color curve instance.
  36226. * @return The cloned curves
  36227. */
  36228. ColorCurves.prototype.clone = function () {
  36229. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  36230. };
  36231. /**
  36232. * Serializes the current color curve instance to a json representation.
  36233. * @return a JSON representation
  36234. */
  36235. ColorCurves.prototype.serialize = function () {
  36236. return BABYLON.SerializationHelper.Serialize(this);
  36237. };
  36238. /**
  36239. * Parses the color curve from a json representation.
  36240. * @param source the JSON source to parse
  36241. * @return The parsed curves
  36242. */
  36243. ColorCurves.Parse = function (source) {
  36244. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  36245. };
  36246. __decorate([
  36247. BABYLON.serialize()
  36248. ], ColorCurves.prototype, "_globalHue", void 0);
  36249. __decorate([
  36250. BABYLON.serialize()
  36251. ], ColorCurves.prototype, "_globalDensity", void 0);
  36252. __decorate([
  36253. BABYLON.serialize()
  36254. ], ColorCurves.prototype, "_globalSaturation", void 0);
  36255. __decorate([
  36256. BABYLON.serialize()
  36257. ], ColorCurves.prototype, "_globalExposure", void 0);
  36258. __decorate([
  36259. BABYLON.serialize()
  36260. ], ColorCurves.prototype, "_highlightsHue", void 0);
  36261. __decorate([
  36262. BABYLON.serialize()
  36263. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  36264. __decorate([
  36265. BABYLON.serialize()
  36266. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  36267. __decorate([
  36268. BABYLON.serialize()
  36269. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  36270. __decorate([
  36271. BABYLON.serialize()
  36272. ], ColorCurves.prototype, "_midtonesHue", void 0);
  36273. __decorate([
  36274. BABYLON.serialize()
  36275. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  36276. __decorate([
  36277. BABYLON.serialize()
  36278. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  36279. __decorate([
  36280. BABYLON.serialize()
  36281. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36282. return ColorCurves;
  36283. }());
  36284. BABYLON.ColorCurves = ColorCurves;
  36285. })(BABYLON || (BABYLON = {}));
  36286. //# sourceMappingURL=babylon.colorCurves.js.map
  36287. //# sourceMappingURL=babylon.behavior.js.map
  36288. var BABYLON;
  36289. (function (BABYLON) {
  36290. /**
  36291. * "Static Class" containing the most commonly used helper while dealing with material for
  36292. * rendering purpose.
  36293. *
  36294. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  36295. *
  36296. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  36297. */
  36298. var MaterialHelper = /** @class */ (function () {
  36299. function MaterialHelper() {
  36300. }
  36301. /**
  36302. * Bind the current view position to an effect.
  36303. * @param effect The effect to be bound
  36304. * @param scene The scene the eyes position is used from
  36305. */
  36306. MaterialHelper.BindEyePosition = function (effect, scene) {
  36307. if (scene._forcedViewPosition) {
  36308. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36309. return;
  36310. }
  36311. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36312. };
  36313. /**
  36314. * Helps preparing the defines values about the UVs in used in the effect.
  36315. * UVs are shared as much as we can accross chanels in the shaders.
  36316. * @param texture The texture we are preparing the UVs for
  36317. * @param defines The defines to update
  36318. * @param key The chanel key "diffuse", "specular"... used in the shader
  36319. */
  36320. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36321. defines._needUVs = true;
  36322. defines[key] = true;
  36323. if (texture.getTextureMatrix().isIdentity(true)) {
  36324. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36325. if (texture.coordinatesIndex === 0) {
  36326. defines["MAINUV1"] = true;
  36327. }
  36328. else {
  36329. defines["MAINUV2"] = true;
  36330. }
  36331. }
  36332. else {
  36333. defines[key + "DIRECTUV"] = 0;
  36334. }
  36335. };
  36336. /**
  36337. * Binds a texture matrix value to its corrsponding uniform
  36338. * @param texture The texture to bind the matrix for
  36339. * @param uniformBuffer The uniform buffer receivin the data
  36340. * @param key The chanel key "diffuse", "specular"... used in the shader
  36341. */
  36342. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36343. var matrix = texture.getTextureMatrix();
  36344. if (!matrix.isIdentity(true)) {
  36345. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36346. }
  36347. };
  36348. /**
  36349. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36350. * @param mesh defines the current mesh
  36351. * @param scene defines the current scene
  36352. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36353. * @param pointsCloud defines if point cloud rendering has to be turned on
  36354. * @param fogEnabled defines if fog has to be turned on
  36355. * @param alphaTest defines if alpha testing has to be turned on
  36356. * @param defines defines the current list of defines
  36357. */
  36358. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36359. if (defines._areMiscDirty) {
  36360. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36361. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36362. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36363. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36364. defines["ALPHATEST"] = alphaTest;
  36365. }
  36366. };
  36367. /**
  36368. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36369. * @param scene defines the current scene
  36370. * @param engine defines the current engine
  36371. * @param defines specifies the list of active defines
  36372. * @param useInstances defines if instances have to be turned on
  36373. */
  36374. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36375. var changed = false;
  36376. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36377. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36378. changed = true;
  36379. }
  36380. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36381. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36382. changed = true;
  36383. }
  36384. if (defines["INSTANCES"] !== useInstances) {
  36385. defines["INSTANCES"] = useInstances;
  36386. changed = true;
  36387. }
  36388. if (changed) {
  36389. defines.markAsUnprocessed();
  36390. }
  36391. };
  36392. /**
  36393. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  36394. * @param mesh The mesh containing the geometry data we will draw
  36395. * @param defines The defines to update
  36396. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  36397. * @param useBones Precise whether bones should be used or not (override mesh info)
  36398. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  36399. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  36400. * @returns false if defines are considered not dirty and have not been checked
  36401. */
  36402. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36403. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36404. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36405. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36406. return false;
  36407. }
  36408. defines._normals = defines._needNormals;
  36409. defines._uvs = defines._needUVs;
  36410. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36411. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36412. defines["TANGENT"] = true;
  36413. }
  36414. if (defines._needUVs) {
  36415. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36416. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36417. }
  36418. else {
  36419. defines["UV1"] = false;
  36420. defines["UV2"] = false;
  36421. }
  36422. if (useVertexColor) {
  36423. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36424. defines["VERTEXCOLOR"] = hasVertexColors;
  36425. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36426. }
  36427. if (useBones) {
  36428. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36429. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36430. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36431. }
  36432. else {
  36433. defines["NUM_BONE_INFLUENCERS"] = 0;
  36434. defines["BonesPerMesh"] = 0;
  36435. }
  36436. }
  36437. if (useMorphTargets) {
  36438. var manager = mesh.morphTargetManager;
  36439. if (manager) {
  36440. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36441. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36442. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36443. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36444. }
  36445. else {
  36446. defines["MORPHTARGETS_TANGENT"] = false;
  36447. defines["MORPHTARGETS_NORMAL"] = false;
  36448. defines["MORPHTARGETS"] = false;
  36449. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36450. }
  36451. }
  36452. return true;
  36453. };
  36454. /**
  36455. * Prepares the defines related to the light information passed in parameter
  36456. * @param scene The scene we are intending to draw
  36457. * @param mesh The mesh the effect is compiling for
  36458. * @param defines The defines to update
  36459. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  36460. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  36461. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  36462. * @returns true if normals will be required for the rest of the effect
  36463. */
  36464. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36465. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36466. if (disableLighting === void 0) { disableLighting = false; }
  36467. if (!defines._areLightsDirty) {
  36468. return defines._needNormals;
  36469. }
  36470. var lightIndex = 0;
  36471. var needNormals = false;
  36472. var needRebuild = false;
  36473. var lightmapMode = false;
  36474. var shadowEnabled = false;
  36475. var specularEnabled = false;
  36476. if (scene.lightsEnabled && !disableLighting) {
  36477. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36478. var light = _a[_i];
  36479. needNormals = true;
  36480. if (defines["LIGHT" + lightIndex] === undefined) {
  36481. needRebuild = true;
  36482. }
  36483. defines["LIGHT" + lightIndex] = true;
  36484. defines["SPOTLIGHT" + lightIndex] = false;
  36485. defines["HEMILIGHT" + lightIndex] = false;
  36486. defines["POINTLIGHT" + lightIndex] = false;
  36487. defines["DIRLIGHT" + lightIndex] = false;
  36488. var type;
  36489. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36490. type = "SPOTLIGHT" + lightIndex;
  36491. var spotLight = light;
  36492. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  36493. }
  36494. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36495. type = "HEMILIGHT" + lightIndex;
  36496. }
  36497. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36498. type = "POINTLIGHT" + lightIndex;
  36499. }
  36500. else {
  36501. type = "DIRLIGHT" + lightIndex;
  36502. }
  36503. defines[type] = true;
  36504. // Specular
  36505. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36506. specularEnabled = true;
  36507. }
  36508. // Shadows
  36509. defines["SHADOW" + lightIndex] = false;
  36510. defines["SHADOWPCF" + lightIndex] = false;
  36511. defines["SHADOWESM" + lightIndex] = false;
  36512. defines["SHADOWCUBE" + lightIndex] = false;
  36513. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36514. var shadowGenerator = light.getShadowGenerator();
  36515. if (shadowGenerator) {
  36516. shadowEnabled = true;
  36517. shadowGenerator.prepareDefines(defines, lightIndex);
  36518. }
  36519. }
  36520. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36521. lightmapMode = true;
  36522. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36523. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36524. }
  36525. else {
  36526. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36527. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36528. }
  36529. lightIndex++;
  36530. if (lightIndex === maxSimultaneousLights)
  36531. break;
  36532. }
  36533. }
  36534. defines["SPECULARTERM"] = specularEnabled;
  36535. defines["SHADOWS"] = shadowEnabled;
  36536. // Resetting all other lights if any
  36537. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36538. if (defines["LIGHT" + index] !== undefined) {
  36539. defines["LIGHT" + index] = false;
  36540. defines["HEMILIGHT" + lightIndex] = false;
  36541. defines["POINTLIGHT" + lightIndex] = false;
  36542. defines["DIRLIGHT" + lightIndex] = false;
  36543. defines["SPOTLIGHT" + lightIndex] = false;
  36544. defines["SHADOW" + lightIndex] = false;
  36545. }
  36546. }
  36547. var caps = scene.getEngine().getCaps();
  36548. if (defines["SHADOWFLOAT"] === undefined) {
  36549. needRebuild = true;
  36550. }
  36551. defines["SHADOWFLOAT"] = shadowEnabled &&
  36552. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36553. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36554. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36555. if (needRebuild) {
  36556. defines.rebuild();
  36557. }
  36558. return needNormals;
  36559. };
  36560. /**
  36561. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  36562. * that won t be acctive due to defines being turned off.
  36563. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  36564. * @param samplersList The samplers list
  36565. * @param defines The defines helping in the list generation
  36566. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  36567. */
  36568. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36569. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36570. var uniformsList;
  36571. var uniformBuffersList = null;
  36572. if (uniformsListOrOptions.uniformsNames) {
  36573. var options = uniformsListOrOptions;
  36574. uniformsList = options.uniformsNames;
  36575. uniformBuffersList = options.uniformBuffersNames;
  36576. samplersList = options.samplers;
  36577. defines = options.defines;
  36578. maxSimultaneousLights = options.maxSimultaneousLights;
  36579. }
  36580. else {
  36581. uniformsList = uniformsListOrOptions;
  36582. if (!samplersList) {
  36583. samplersList = [];
  36584. }
  36585. }
  36586. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36587. if (!defines["LIGHT" + lightIndex]) {
  36588. break;
  36589. }
  36590. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36591. if (uniformBuffersList) {
  36592. uniformBuffersList.push("Light" + lightIndex);
  36593. }
  36594. samplersList.push("shadowSampler" + lightIndex);
  36595. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  36596. samplersList.push("projectionLightSampler" + lightIndex);
  36597. uniformsList.push("textureProjectionMatrix" + lightIndex);
  36598. }
  36599. }
  36600. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36601. uniformsList.push("morphTargetInfluences");
  36602. }
  36603. };
  36604. /**
  36605. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  36606. * @param defines The defines to update while falling back
  36607. * @param fallbacks The authorized effect fallbacks
  36608. * @param maxSimultaneousLights The maximum number of lights allowed
  36609. * @param rank the current rank of the Effect
  36610. * @returns The newly affected rank
  36611. */
  36612. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36613. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36614. if (rank === void 0) { rank = 0; }
  36615. var lightFallbackRank = 0;
  36616. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36617. if (!defines["LIGHT" + lightIndex]) {
  36618. break;
  36619. }
  36620. if (lightIndex > 0) {
  36621. lightFallbackRank = rank + lightIndex;
  36622. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36623. }
  36624. if (!defines["SHADOWS"]) {
  36625. if (defines["SHADOW" + lightIndex]) {
  36626. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36627. }
  36628. if (defines["SHADOWPCF" + lightIndex]) {
  36629. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36630. }
  36631. if (defines["SHADOWESM" + lightIndex]) {
  36632. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36633. }
  36634. }
  36635. }
  36636. return lightFallbackRank++;
  36637. };
  36638. /**
  36639. * Prepares the list of attributes required for morph targets according to the effect defines.
  36640. * @param attribs The current list of supported attribs
  36641. * @param mesh The mesh to prepare the morph targets attributes for
  36642. * @param defines The current Defines of the effect
  36643. */
  36644. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36645. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36646. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36647. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36648. var manager = mesh.morphTargetManager;
  36649. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36650. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36651. for (var index = 0; index < influencers; index++) {
  36652. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36653. if (normal) {
  36654. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36655. }
  36656. if (tangent) {
  36657. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36658. }
  36659. if (attribs.length > maxAttributesCount) {
  36660. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36661. }
  36662. }
  36663. }
  36664. };
  36665. /**
  36666. * Prepares the list of attributes required for bones according to the effect defines.
  36667. * @param attribs The current list of supported attribs
  36668. * @param mesh The mesh to prepare the bones attributes for
  36669. * @param defines The current Defines of the effect
  36670. * @param fallbacks The current efffect fallback strategy
  36671. */
  36672. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36673. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36674. fallbacks.addCPUSkinningFallback(0, mesh);
  36675. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36676. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36677. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36678. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36679. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36680. }
  36681. }
  36682. };
  36683. /**
  36684. * Prepares the list of attributes required for instances according to the effect defines.
  36685. * @param attribs The current list of supported attribs
  36686. * @param defines The current Defines of the effect
  36687. */
  36688. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36689. if (defines["INSTANCES"]) {
  36690. attribs.push("world0");
  36691. attribs.push("world1");
  36692. attribs.push("world2");
  36693. attribs.push("world3");
  36694. }
  36695. };
  36696. /**
  36697. * Binds the light shadow information to the effect for the given mesh.
  36698. * @param light The light containing the generator
  36699. * @param scene The scene the lights belongs to
  36700. * @param mesh The mesh we are binding the information to render
  36701. * @param lightIndex The light index in the effect used to render the mesh
  36702. * @param effect The effect we are binding the data to
  36703. */
  36704. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36705. if (light.shadowEnabled && mesh.receiveShadows) {
  36706. var shadowGenerator = light.getShadowGenerator();
  36707. if (shadowGenerator) {
  36708. shadowGenerator.bindShadowLight(lightIndex, effect);
  36709. }
  36710. }
  36711. };
  36712. /**
  36713. * Binds the light information to the effect.
  36714. * @param light The light containing the generator
  36715. * @param effect The effect we are binding the data to
  36716. * @param lightIndex The light index in the effect used to render
  36717. */
  36718. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36719. light.transferToEffect(effect, lightIndex + "");
  36720. };
  36721. /**
  36722. * Binds the lights information from the scene to the effect for the given mesh.
  36723. * @param scene The scene the lights belongs to
  36724. * @param mesh The mesh we are binding the information to render
  36725. * @param effect The effect we are binding the data to
  36726. * @param defines The generated defines for the effect
  36727. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  36728. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  36729. */
  36730. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36731. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36732. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36733. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36734. for (var i = 0; i < len; i++) {
  36735. var light = mesh._lightSources[i];
  36736. var iAsString = i.toString();
  36737. var scaledIntensity = light.getScaledIntensity();
  36738. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36739. MaterialHelper.BindLightProperties(light, effect, i);
  36740. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36741. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36742. if (defines["SPECULARTERM"]) {
  36743. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36744. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36745. }
  36746. // Shadows
  36747. if (scene.shadowsEnabled) {
  36748. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36749. }
  36750. light._uniformBuffer.update();
  36751. }
  36752. };
  36753. /**
  36754. * Binds the fog information from the scene to the effect for the given mesh.
  36755. * @param scene The scene the lights belongs to
  36756. * @param mesh The mesh we are binding the information to render
  36757. * @param effect The effect we are binding the data to
  36758. */
  36759. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36760. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36761. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36762. effect.setColor3("vFogColor", scene.fogColor);
  36763. }
  36764. };
  36765. /**
  36766. * Binds the bones information from the mesh to the effect.
  36767. * @param mesh The mesh we are binding the information to render
  36768. * @param effect The effect we are binding the data to
  36769. */
  36770. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36771. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36772. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36773. if (matrices && effect) {
  36774. effect.setMatrices("mBones", matrices);
  36775. }
  36776. }
  36777. };
  36778. /**
  36779. * Binds the morph targets information from the mesh to the effect.
  36780. * @param abstractMesh The mesh we are binding the information to render
  36781. * @param effect The effect we are binding the data to
  36782. */
  36783. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36784. var manager = abstractMesh.morphTargetManager;
  36785. if (!abstractMesh || !manager) {
  36786. return;
  36787. }
  36788. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36789. };
  36790. /**
  36791. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  36792. * @param defines The generated defines used in the effect
  36793. * @param effect The effect we are binding the data to
  36794. * @param scene The scene we are willing to render with logarithmic scale for
  36795. */
  36796. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36797. if (defines["LOGARITHMICDEPTH"]) {
  36798. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36799. }
  36800. };
  36801. /**
  36802. * Binds the clip plane information from the scene to the effect.
  36803. * @param scene The scene the clip plane information are extracted from
  36804. * @param effect The effect we are binding the data to
  36805. */
  36806. MaterialHelper.BindClipPlane = function (effect, scene) {
  36807. if (scene.clipPlane) {
  36808. var clipPlane = scene.clipPlane;
  36809. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36810. }
  36811. };
  36812. return MaterialHelper;
  36813. }());
  36814. BABYLON.MaterialHelper = MaterialHelper;
  36815. })(BABYLON || (BABYLON = {}));
  36816. //# sourceMappingURL=babylon.materialHelper.js.map
  36817. var BABYLON;
  36818. (function (BABYLON) {
  36819. var PushMaterial = /** @class */ (function (_super) {
  36820. __extends(PushMaterial, _super);
  36821. function PushMaterial(name, scene) {
  36822. var _this = _super.call(this, name, scene) || this;
  36823. _this.storeEffectOnSubMeshes = true;
  36824. return _this;
  36825. }
  36826. PushMaterial.prototype.getEffect = function () {
  36827. return this._activeEffect;
  36828. };
  36829. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36830. if (!mesh) {
  36831. return false;
  36832. }
  36833. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36834. return true;
  36835. }
  36836. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36837. };
  36838. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36839. this._activeEffect.setMatrix("world", world);
  36840. };
  36841. PushMaterial.prototype.bind = function (world, mesh) {
  36842. if (!mesh) {
  36843. return;
  36844. }
  36845. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36846. };
  36847. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36848. if (effect === void 0) { effect = null; }
  36849. _super.prototype._afterBind.call(this, mesh);
  36850. this.getScene()._cachedEffect = effect;
  36851. };
  36852. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36853. if (visibility === void 0) { visibility = 1; }
  36854. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36855. };
  36856. return PushMaterial;
  36857. }(BABYLON.Material));
  36858. BABYLON.PushMaterial = PushMaterial;
  36859. })(BABYLON || (BABYLON = {}));
  36860. //# sourceMappingURL=babylon.pushMaterial.js.map
  36861. var BABYLON;
  36862. (function (BABYLON) {
  36863. var StandardMaterialDefines = /** @class */ (function (_super) {
  36864. __extends(StandardMaterialDefines, _super);
  36865. function StandardMaterialDefines() {
  36866. var _this = _super.call(this) || this;
  36867. _this.MAINUV1 = false;
  36868. _this.MAINUV2 = false;
  36869. _this.DIFFUSE = false;
  36870. _this.DIFFUSEDIRECTUV = 0;
  36871. _this.AMBIENT = false;
  36872. _this.AMBIENTDIRECTUV = 0;
  36873. _this.OPACITY = false;
  36874. _this.OPACITYDIRECTUV = 0;
  36875. _this.OPACITYRGB = false;
  36876. _this.REFLECTION = false;
  36877. _this.EMISSIVE = false;
  36878. _this.EMISSIVEDIRECTUV = 0;
  36879. _this.SPECULAR = false;
  36880. _this.SPECULARDIRECTUV = 0;
  36881. _this.BUMP = false;
  36882. _this.BUMPDIRECTUV = 0;
  36883. _this.PARALLAX = false;
  36884. _this.PARALLAXOCCLUSION = false;
  36885. _this.SPECULAROVERALPHA = false;
  36886. _this.CLIPPLANE = false;
  36887. _this.ALPHATEST = false;
  36888. _this.DEPTHPREPASS = false;
  36889. _this.ALPHAFROMDIFFUSE = false;
  36890. _this.POINTSIZE = false;
  36891. _this.FOG = false;
  36892. _this.SPECULARTERM = false;
  36893. _this.DIFFUSEFRESNEL = false;
  36894. _this.OPACITYFRESNEL = false;
  36895. _this.REFLECTIONFRESNEL = false;
  36896. _this.REFRACTIONFRESNEL = false;
  36897. _this.EMISSIVEFRESNEL = false;
  36898. _this.FRESNEL = false;
  36899. _this.NORMAL = false;
  36900. _this.UV1 = false;
  36901. _this.UV2 = false;
  36902. _this.VERTEXCOLOR = false;
  36903. _this.VERTEXALPHA = false;
  36904. _this.NUM_BONE_INFLUENCERS = 0;
  36905. _this.BonesPerMesh = 0;
  36906. _this.INSTANCES = false;
  36907. _this.GLOSSINESS = false;
  36908. _this.ROUGHNESS = false;
  36909. _this.EMISSIVEASILLUMINATION = false;
  36910. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36911. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36912. _this.LIGHTMAP = false;
  36913. _this.LIGHTMAPDIRECTUV = 0;
  36914. _this.USELIGHTMAPASSHADOWMAP = false;
  36915. _this.REFLECTIONMAP_3D = false;
  36916. _this.REFLECTIONMAP_SPHERICAL = false;
  36917. _this.REFLECTIONMAP_PLANAR = false;
  36918. _this.REFLECTIONMAP_CUBIC = false;
  36919. _this.REFLECTIONMAP_PROJECTION = false;
  36920. _this.REFLECTIONMAP_SKYBOX = false;
  36921. _this.REFLECTIONMAP_EXPLICIT = false;
  36922. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36923. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36924. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36925. _this.INVERTCUBICMAP = false;
  36926. _this.LOGARITHMICDEPTH = false;
  36927. _this.REFRACTION = false;
  36928. _this.REFRACTIONMAP_3D = false;
  36929. _this.REFLECTIONOVERALPHA = false;
  36930. _this.TWOSIDEDLIGHTING = false;
  36931. _this.SHADOWFLOAT = false;
  36932. _this.MORPHTARGETS = false;
  36933. _this.MORPHTARGETS_NORMAL = false;
  36934. _this.MORPHTARGETS_TANGENT = false;
  36935. _this.NUM_MORPH_INFLUENCERS = 0;
  36936. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36937. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36938. _this.IMAGEPROCESSING = false;
  36939. _this.VIGNETTE = false;
  36940. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36941. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36942. _this.TONEMAPPING = false;
  36943. _this.CONTRAST = false;
  36944. _this.COLORCURVES = false;
  36945. _this.COLORGRADING = false;
  36946. _this.COLORGRADING3D = false;
  36947. _this.SAMPLER3DGREENDEPTH = false;
  36948. _this.SAMPLER3DBGRMAP = false;
  36949. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36950. _this.EXPOSURE = false;
  36951. _this.rebuild();
  36952. return _this;
  36953. }
  36954. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36955. var modes = [
  36956. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36957. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36958. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36959. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36960. ];
  36961. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36962. var mode = modes_1[_i];
  36963. this[mode] = (mode === modeToEnable);
  36964. }
  36965. };
  36966. return StandardMaterialDefines;
  36967. }(BABYLON.MaterialDefines));
  36968. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36969. var StandardMaterial = /** @class */ (function (_super) {
  36970. __extends(StandardMaterial, _super);
  36971. function StandardMaterial(name, scene) {
  36972. var _this = _super.call(this, name, scene) || this;
  36973. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36974. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36975. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36976. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36977. _this.specularPower = 64;
  36978. _this._useAlphaFromDiffuseTexture = false;
  36979. _this._useEmissiveAsIllumination = false;
  36980. _this._linkEmissiveWithDiffuse = false;
  36981. _this._useSpecularOverAlpha = false;
  36982. _this._useReflectionOverAlpha = false;
  36983. _this._disableLighting = false;
  36984. _this._useParallax = false;
  36985. _this._useParallaxOcclusion = false;
  36986. _this.parallaxScaleBias = 0.05;
  36987. _this._roughness = 0;
  36988. _this.indexOfRefraction = 0.98;
  36989. _this.invertRefractionY = true;
  36990. _this._useLightmapAsShadowmap = false;
  36991. _this._useReflectionFresnelFromSpecular = false;
  36992. _this._useGlossinessFromSpecularMapAlpha = false;
  36993. _this._maxSimultaneousLights = 4;
  36994. /**
  36995. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36996. */
  36997. _this._invertNormalMapX = false;
  36998. /**
  36999. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37000. */
  37001. _this._invertNormalMapY = false;
  37002. /**
  37003. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37004. */
  37005. _this._twoSidedLighting = false;
  37006. _this._renderTargets = new BABYLON.SmartArray(16);
  37007. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37008. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37009. // Setup the default processing configuration to the scene.
  37010. _this._attachImageProcessingConfiguration(null);
  37011. _this.getRenderTargetTextures = function () {
  37012. _this._renderTargets.reset();
  37013. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37014. _this._renderTargets.push(_this._reflectionTexture);
  37015. }
  37016. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37017. _this._renderTargets.push(_this._refractionTexture);
  37018. }
  37019. return _this._renderTargets;
  37020. };
  37021. return _this;
  37022. }
  37023. ;
  37024. ;
  37025. ;
  37026. ;
  37027. ;
  37028. ;
  37029. ;
  37030. ;
  37031. ;
  37032. ;
  37033. ;
  37034. ;
  37035. ;
  37036. ;
  37037. ;
  37038. ;
  37039. ;
  37040. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  37041. /**
  37042. * Gets the image processing configuration used either in this material.
  37043. */
  37044. get: function () {
  37045. return this._imageProcessingConfiguration;
  37046. },
  37047. /**
  37048. * Sets the Default image processing configuration used either in the this material.
  37049. *
  37050. * If sets to null, the scene one is in use.
  37051. */
  37052. set: function (value) {
  37053. this._attachImageProcessingConfiguration(value);
  37054. // Ensure the effect will be rebuilt.
  37055. this._markAllSubMeshesAsTexturesDirty();
  37056. },
  37057. enumerable: true,
  37058. configurable: true
  37059. });
  37060. /**
  37061. * Attaches a new image processing configuration to the Standard Material.
  37062. * @param configuration
  37063. */
  37064. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37065. var _this = this;
  37066. if (configuration === this._imageProcessingConfiguration) {
  37067. return;
  37068. }
  37069. // Detaches observer.
  37070. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37071. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37072. }
  37073. // Pick the scene configuration if needed.
  37074. if (!configuration) {
  37075. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37076. }
  37077. else {
  37078. this._imageProcessingConfiguration = configuration;
  37079. }
  37080. // Attaches observer.
  37081. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37082. _this._markAllSubMeshesAsImageProcessingDirty();
  37083. });
  37084. };
  37085. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  37086. /**
  37087. * Gets wether the color curves effect is enabled.
  37088. */
  37089. get: function () {
  37090. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37091. },
  37092. /**
  37093. * Sets wether the color curves effect is enabled.
  37094. */
  37095. set: function (value) {
  37096. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37097. },
  37098. enumerable: true,
  37099. configurable: true
  37100. });
  37101. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  37102. /**
  37103. * Gets wether the color grading effect is enabled.
  37104. */
  37105. get: function () {
  37106. return this.imageProcessingConfiguration.colorGradingEnabled;
  37107. },
  37108. /**
  37109. * Gets wether the color grading effect is enabled.
  37110. */
  37111. set: function (value) {
  37112. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37113. },
  37114. enumerable: true,
  37115. configurable: true
  37116. });
  37117. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  37118. /**
  37119. * Gets wether tonemapping is enabled or not.
  37120. */
  37121. get: function () {
  37122. return this._imageProcessingConfiguration.toneMappingEnabled;
  37123. },
  37124. /**
  37125. * Sets wether tonemapping is enabled or not
  37126. */
  37127. set: function (value) {
  37128. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37129. },
  37130. enumerable: true,
  37131. configurable: true
  37132. });
  37133. ;
  37134. ;
  37135. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  37136. /**
  37137. * The camera exposure used on this material.
  37138. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37139. * This corresponds to a photographic exposure.
  37140. */
  37141. get: function () {
  37142. return this._imageProcessingConfiguration.exposure;
  37143. },
  37144. /**
  37145. * The camera exposure used on this material.
  37146. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37147. * This corresponds to a photographic exposure.
  37148. */
  37149. set: function (value) {
  37150. this._imageProcessingConfiguration.exposure = value;
  37151. },
  37152. enumerable: true,
  37153. configurable: true
  37154. });
  37155. ;
  37156. ;
  37157. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  37158. /**
  37159. * Gets The camera contrast used on this material.
  37160. */
  37161. get: function () {
  37162. return this._imageProcessingConfiguration.contrast;
  37163. },
  37164. /**
  37165. * Sets The camera contrast used on this material.
  37166. */
  37167. set: function (value) {
  37168. this._imageProcessingConfiguration.contrast = value;
  37169. },
  37170. enumerable: true,
  37171. configurable: true
  37172. });
  37173. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  37174. /**
  37175. * Gets the Color Grading 2D Lookup Texture.
  37176. */
  37177. get: function () {
  37178. return this._imageProcessingConfiguration.colorGradingTexture;
  37179. },
  37180. /**
  37181. * Sets the Color Grading 2D Lookup Texture.
  37182. */
  37183. set: function (value) {
  37184. this._imageProcessingConfiguration.colorGradingTexture = value;
  37185. },
  37186. enumerable: true,
  37187. configurable: true
  37188. });
  37189. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  37190. /**
  37191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37193. * 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;
  37194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37195. */
  37196. get: function () {
  37197. return this._imageProcessingConfiguration.colorCurves;
  37198. },
  37199. /**
  37200. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37201. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37202. * 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;
  37203. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37204. */
  37205. set: function (value) {
  37206. this._imageProcessingConfiguration.colorCurves = value;
  37207. },
  37208. enumerable: true,
  37209. configurable: true
  37210. });
  37211. StandardMaterial.prototype.getClassName = function () {
  37212. return "StandardMaterial";
  37213. };
  37214. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  37215. get: function () {
  37216. return this._useLogarithmicDepth;
  37217. },
  37218. set: function (value) {
  37219. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37220. this._markAllSubMeshesAsMiscDirty();
  37221. },
  37222. enumerable: true,
  37223. configurable: true
  37224. });
  37225. StandardMaterial.prototype.needAlphaBlending = function () {
  37226. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  37227. };
  37228. StandardMaterial.prototype.needAlphaTesting = function () {
  37229. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  37230. };
  37231. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  37232. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  37233. };
  37234. StandardMaterial.prototype.getAlphaTestTexture = function () {
  37235. return this._diffuseTexture;
  37236. };
  37237. /**
  37238. * Child classes can use it to update shaders
  37239. */
  37240. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37241. if (useInstances === void 0) { useInstances = false; }
  37242. if (subMesh.effect && this.isFrozen) {
  37243. if (this._wasPreviouslyReady && subMesh.effect) {
  37244. return true;
  37245. }
  37246. }
  37247. if (!subMesh._materialDefines) {
  37248. subMesh._materialDefines = new StandardMaterialDefines();
  37249. }
  37250. var scene = this.getScene();
  37251. var defines = subMesh._materialDefines;
  37252. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37253. if (defines._renderId === scene.getRenderId()) {
  37254. return true;
  37255. }
  37256. }
  37257. var engine = scene.getEngine();
  37258. // Lights
  37259. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37260. // Textures
  37261. if (defines._areTexturesDirty) {
  37262. defines._needUVs = false;
  37263. defines.MAINUV1 = false;
  37264. defines.MAINUV2 = false;
  37265. if (scene.texturesEnabled) {
  37266. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37267. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  37268. return false;
  37269. }
  37270. else {
  37271. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  37272. }
  37273. }
  37274. else {
  37275. defines.DIFFUSE = false;
  37276. }
  37277. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37278. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37279. return false;
  37280. }
  37281. else {
  37282. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37283. }
  37284. }
  37285. else {
  37286. defines.AMBIENT = false;
  37287. }
  37288. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37289. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37290. return false;
  37291. }
  37292. else {
  37293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37294. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37295. }
  37296. }
  37297. else {
  37298. defines.OPACITY = false;
  37299. }
  37300. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37301. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  37302. return false;
  37303. }
  37304. else {
  37305. defines._needNormals = true;
  37306. defines.REFLECTION = true;
  37307. defines.ROUGHNESS = (this._roughness > 0);
  37308. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  37309. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  37310. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  37311. switch (this._reflectionTexture.coordinatesMode) {
  37312. case BABYLON.Texture.CUBIC_MODE:
  37313. case BABYLON.Texture.INVCUBIC_MODE:
  37314. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  37315. break;
  37316. case BABYLON.Texture.EXPLICIT_MODE:
  37317. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  37318. break;
  37319. case BABYLON.Texture.PLANAR_MODE:
  37320. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  37321. break;
  37322. case BABYLON.Texture.PROJECTION_MODE:
  37323. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  37324. break;
  37325. case BABYLON.Texture.SKYBOX_MODE:
  37326. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  37327. break;
  37328. case BABYLON.Texture.SPHERICAL_MODE:
  37329. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  37330. break;
  37331. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37332. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  37333. break;
  37334. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37335. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  37336. break;
  37337. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37338. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  37339. break;
  37340. }
  37341. }
  37342. }
  37343. else {
  37344. defines.REFLECTION = false;
  37345. }
  37346. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37347. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37348. return false;
  37349. }
  37350. else {
  37351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37352. }
  37353. }
  37354. else {
  37355. defines.EMISSIVE = false;
  37356. }
  37357. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37358. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37359. return false;
  37360. }
  37361. else {
  37362. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37363. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37364. }
  37365. }
  37366. else {
  37367. defines.LIGHTMAP = false;
  37368. }
  37369. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37370. if (!this._specularTexture.isReadyOrNotBlocking()) {
  37371. return false;
  37372. }
  37373. else {
  37374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  37375. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  37376. }
  37377. }
  37378. else {
  37379. defines.SPECULAR = false;
  37380. }
  37381. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  37382. // Bump texure can not be not blocking.
  37383. if (!this._bumpTexture.isReady()) {
  37384. return false;
  37385. }
  37386. else {
  37387. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37388. defines.PARALLAX = this._useParallax;
  37389. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  37390. }
  37391. }
  37392. else {
  37393. defines.BUMP = false;
  37394. }
  37395. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37396. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  37397. return false;
  37398. }
  37399. else {
  37400. defines._needUVs = true;
  37401. defines.REFRACTION = true;
  37402. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  37403. }
  37404. }
  37405. else {
  37406. defines.REFRACTION = false;
  37407. }
  37408. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  37409. }
  37410. else {
  37411. defines.DIFFUSE = false;
  37412. defines.AMBIENT = false;
  37413. defines.OPACITY = false;
  37414. defines.REFLECTION = false;
  37415. defines.EMISSIVE = false;
  37416. defines.LIGHTMAP = false;
  37417. defines.BUMP = false;
  37418. defines.REFRACTION = false;
  37419. }
  37420. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37421. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37422. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37423. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37424. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37425. }
  37426. if (defines._areImageProcessingDirty) {
  37427. if (!this._imageProcessingConfiguration.isReady()) {
  37428. return false;
  37429. }
  37430. this._imageProcessingConfiguration.prepareDefines(defines);
  37431. }
  37432. if (defines._areFresnelDirty) {
  37433. if (StandardMaterial.FresnelEnabled) {
  37434. // Fresnel
  37435. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37436. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37437. this._reflectionFresnelParameters) {
  37438. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37439. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37440. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37441. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37442. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37443. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37444. defines._needNormals = true;
  37445. defines.FRESNEL = true;
  37446. }
  37447. }
  37448. else {
  37449. defines.FRESNEL = false;
  37450. }
  37451. }
  37452. // Misc.
  37453. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37454. // Attribs
  37455. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37456. // Values that need to be evaluated on every frame
  37457. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37458. // Get correct effect
  37459. if (defines.isDirty) {
  37460. defines.markAsProcessed();
  37461. scene.resetCachedMaterial();
  37462. // Fallbacks
  37463. var fallbacks = new BABYLON.EffectFallbacks();
  37464. if (defines.REFLECTION) {
  37465. fallbacks.addFallback(0, "REFLECTION");
  37466. }
  37467. if (defines.SPECULAR) {
  37468. fallbacks.addFallback(0, "SPECULAR");
  37469. }
  37470. if (defines.BUMP) {
  37471. fallbacks.addFallback(0, "BUMP");
  37472. }
  37473. if (defines.PARALLAX) {
  37474. fallbacks.addFallback(1, "PARALLAX");
  37475. }
  37476. if (defines.PARALLAXOCCLUSION) {
  37477. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37478. }
  37479. if (defines.SPECULAROVERALPHA) {
  37480. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37481. }
  37482. if (defines.FOG) {
  37483. fallbacks.addFallback(1, "FOG");
  37484. }
  37485. if (defines.POINTSIZE) {
  37486. fallbacks.addFallback(0, "POINTSIZE");
  37487. }
  37488. if (defines.LOGARITHMICDEPTH) {
  37489. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37490. }
  37491. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37492. if (defines.SPECULARTERM) {
  37493. fallbacks.addFallback(0, "SPECULARTERM");
  37494. }
  37495. if (defines.DIFFUSEFRESNEL) {
  37496. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37497. }
  37498. if (defines.OPACITYFRESNEL) {
  37499. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37500. }
  37501. if (defines.REFLECTIONFRESNEL) {
  37502. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37503. }
  37504. if (defines.EMISSIVEFRESNEL) {
  37505. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37506. }
  37507. if (defines.FRESNEL) {
  37508. fallbacks.addFallback(4, "FRESNEL");
  37509. }
  37510. //Attributes
  37511. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37512. if (defines.NORMAL) {
  37513. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37514. }
  37515. if (defines.UV1) {
  37516. attribs.push(BABYLON.VertexBuffer.UVKind);
  37517. }
  37518. if (defines.UV2) {
  37519. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37520. }
  37521. if (defines.VERTEXCOLOR) {
  37522. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37523. }
  37524. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37525. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37526. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37527. var shaderName = "default";
  37528. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37529. "vFogInfos", "vFogColor", "pointSize",
  37530. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37531. "mBones",
  37532. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37533. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37534. "logarithmicDepthConstant", "vTangentSpaceParams"
  37535. ];
  37536. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37537. var uniformBuffers = ["Material", "Scene"];
  37538. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37539. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37540. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37541. uniformsNames: uniforms,
  37542. uniformBuffersNames: uniformBuffers,
  37543. samplers: samplers,
  37544. defines: defines,
  37545. maxSimultaneousLights: this._maxSimultaneousLights
  37546. });
  37547. if (this.customShaderNameResolve) {
  37548. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37549. }
  37550. var join = defines.toString();
  37551. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37552. attributes: attribs,
  37553. uniformsNames: uniforms,
  37554. uniformBuffersNames: uniformBuffers,
  37555. samplers: samplers,
  37556. defines: join,
  37557. fallbacks: fallbacks,
  37558. onCompiled: this.onCompiled,
  37559. onError: this.onError,
  37560. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37561. }, engine), defines);
  37562. this.buildUniformLayout();
  37563. }
  37564. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37565. return false;
  37566. }
  37567. defines._renderId = scene.getRenderId();
  37568. this._wasPreviouslyReady = true;
  37569. return true;
  37570. };
  37571. StandardMaterial.prototype.buildUniformLayout = function () {
  37572. // Order is important !
  37573. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37574. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37575. this._uniformBuffer.addUniform("opacityParts", 4);
  37576. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37577. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37578. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37579. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37580. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37581. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37582. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37583. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37584. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37585. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37586. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37587. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37588. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37589. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37590. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37591. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37592. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37593. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37594. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37595. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37596. this._uniformBuffer.addUniform("specularMatrix", 16);
  37597. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37598. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37599. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37600. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37601. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37602. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37603. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37604. this._uniformBuffer.addUniform("pointSize", 1);
  37605. this._uniformBuffer.create();
  37606. };
  37607. StandardMaterial.prototype.unbind = function () {
  37608. if (this._activeEffect) {
  37609. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37610. this._activeEffect.setTexture("reflection2DSampler", null);
  37611. }
  37612. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37613. this._activeEffect.setTexture("refraction2DSampler", null);
  37614. }
  37615. }
  37616. _super.prototype.unbind.call(this);
  37617. };
  37618. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37619. var scene = this.getScene();
  37620. var defines = subMesh._materialDefines;
  37621. if (!defines) {
  37622. return;
  37623. }
  37624. var effect = subMesh.effect;
  37625. if (!effect) {
  37626. return;
  37627. }
  37628. this._activeEffect = effect;
  37629. // Matrices
  37630. this.bindOnlyWorldMatrix(world);
  37631. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37632. // Bones
  37633. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37634. if (mustRebind) {
  37635. this._uniformBuffer.bindToEffect(effect, "Material");
  37636. this.bindViewProjection(effect);
  37637. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37638. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37639. // Fresnel
  37640. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37641. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37642. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37643. }
  37644. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37645. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37646. }
  37647. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37648. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37649. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37650. }
  37651. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37652. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37653. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37654. }
  37655. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37656. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37657. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37658. }
  37659. }
  37660. // Textures
  37661. if (scene.texturesEnabled) {
  37662. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37663. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37664. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37665. }
  37666. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37667. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37668. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37669. }
  37670. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37671. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37672. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37673. }
  37674. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37675. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37676. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37677. }
  37678. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37679. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37680. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37681. }
  37682. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37683. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37684. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37685. }
  37686. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37687. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37688. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37689. }
  37690. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37691. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37692. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37693. if (scene._mirroredCameraPosition) {
  37694. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37695. }
  37696. else {
  37697. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37698. }
  37699. }
  37700. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37701. var depth = 1.0;
  37702. if (!this._refractionTexture.isCube) {
  37703. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37704. if (this._refractionTexture.depth) {
  37705. depth = this._refractionTexture.depth;
  37706. }
  37707. }
  37708. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37709. }
  37710. }
  37711. // Point size
  37712. if (this.pointsCloud) {
  37713. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37714. }
  37715. if (defines.SPECULARTERM) {
  37716. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37717. }
  37718. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37719. // Diffuse
  37720. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37721. }
  37722. // Textures
  37723. if (scene.texturesEnabled) {
  37724. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37725. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37726. }
  37727. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37728. effect.setTexture("ambientSampler", this._ambientTexture);
  37729. }
  37730. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37731. effect.setTexture("opacitySampler", this._opacityTexture);
  37732. }
  37733. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37734. if (this._reflectionTexture.isCube) {
  37735. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37736. }
  37737. else {
  37738. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37739. }
  37740. }
  37741. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37742. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37743. }
  37744. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37745. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37746. }
  37747. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37748. effect.setTexture("specularSampler", this._specularTexture);
  37749. }
  37750. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37751. effect.setTexture("bumpSampler", this._bumpTexture);
  37752. }
  37753. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37754. var depth = 1.0;
  37755. if (this._refractionTexture.isCube) {
  37756. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37757. }
  37758. else {
  37759. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37760. }
  37761. }
  37762. }
  37763. // Clip plane
  37764. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37765. // Colors
  37766. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37767. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37768. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37769. }
  37770. if (mustRebind || !this.isFrozen) {
  37771. // Lights
  37772. if (scene.lightsEnabled && !this._disableLighting) {
  37773. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37774. }
  37775. // View
  37776. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37777. this.bindView(effect);
  37778. }
  37779. // Fog
  37780. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37781. // Morph targets
  37782. if (defines.NUM_MORPH_INFLUENCERS) {
  37783. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37784. }
  37785. // Log. depth
  37786. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37787. // image processing
  37788. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37789. this._imageProcessingConfiguration.bind(this._activeEffect);
  37790. }
  37791. }
  37792. this._uniformBuffer.update();
  37793. this._afterBind(mesh, this._activeEffect);
  37794. };
  37795. StandardMaterial.prototype.getAnimatables = function () {
  37796. var results = [];
  37797. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37798. results.push(this._diffuseTexture);
  37799. }
  37800. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37801. results.push(this._ambientTexture);
  37802. }
  37803. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37804. results.push(this._opacityTexture);
  37805. }
  37806. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37807. results.push(this._reflectionTexture);
  37808. }
  37809. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37810. results.push(this._emissiveTexture);
  37811. }
  37812. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37813. results.push(this._specularTexture);
  37814. }
  37815. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37816. results.push(this._bumpTexture);
  37817. }
  37818. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37819. results.push(this._lightmapTexture);
  37820. }
  37821. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37822. results.push(this._refractionTexture);
  37823. }
  37824. return results;
  37825. };
  37826. StandardMaterial.prototype.getActiveTextures = function () {
  37827. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37828. if (this._diffuseTexture) {
  37829. activeTextures.push(this._diffuseTexture);
  37830. }
  37831. if (this._ambientTexture) {
  37832. activeTextures.push(this._ambientTexture);
  37833. }
  37834. if (this._opacityTexture) {
  37835. activeTextures.push(this._opacityTexture);
  37836. }
  37837. if (this._reflectionTexture) {
  37838. activeTextures.push(this._reflectionTexture);
  37839. }
  37840. if (this._emissiveTexture) {
  37841. activeTextures.push(this._emissiveTexture);
  37842. }
  37843. if (this._specularTexture) {
  37844. activeTextures.push(this._specularTexture);
  37845. }
  37846. if (this._bumpTexture) {
  37847. activeTextures.push(this._bumpTexture);
  37848. }
  37849. if (this._lightmapTexture) {
  37850. activeTextures.push(this._lightmapTexture);
  37851. }
  37852. if (this._refractionTexture) {
  37853. activeTextures.push(this._refractionTexture);
  37854. }
  37855. return activeTextures;
  37856. };
  37857. StandardMaterial.prototype.hasTexture = function (texture) {
  37858. if (_super.prototype.hasTexture.call(this, texture)) {
  37859. return true;
  37860. }
  37861. if (this._diffuseTexture === texture) {
  37862. return true;
  37863. }
  37864. if (this._ambientTexture === texture) {
  37865. return true;
  37866. }
  37867. if (this._opacityTexture === texture) {
  37868. return true;
  37869. }
  37870. if (this._reflectionTexture === texture) {
  37871. return true;
  37872. }
  37873. if (this._emissiveTexture === texture) {
  37874. return true;
  37875. }
  37876. if (this._specularTexture === texture) {
  37877. return true;
  37878. }
  37879. if (this._bumpTexture === texture) {
  37880. return true;
  37881. }
  37882. if (this._lightmapTexture === texture) {
  37883. return true;
  37884. }
  37885. if (this._refractionTexture === texture) {
  37886. return true;
  37887. }
  37888. return false;
  37889. };
  37890. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37891. if (forceDisposeTextures) {
  37892. if (this._diffuseTexture) {
  37893. this._diffuseTexture.dispose();
  37894. }
  37895. if (this._ambientTexture) {
  37896. this._ambientTexture.dispose();
  37897. }
  37898. if (this._opacityTexture) {
  37899. this._opacityTexture.dispose();
  37900. }
  37901. if (this._reflectionTexture) {
  37902. this._reflectionTexture.dispose();
  37903. }
  37904. if (this._emissiveTexture) {
  37905. this._emissiveTexture.dispose();
  37906. }
  37907. if (this._specularTexture) {
  37908. this._specularTexture.dispose();
  37909. }
  37910. if (this._bumpTexture) {
  37911. this._bumpTexture.dispose();
  37912. }
  37913. if (this._lightmapTexture) {
  37914. this._lightmapTexture.dispose();
  37915. }
  37916. if (this._refractionTexture) {
  37917. this._refractionTexture.dispose();
  37918. }
  37919. }
  37920. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37921. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37922. }
  37923. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37924. };
  37925. StandardMaterial.prototype.clone = function (name) {
  37926. var _this = this;
  37927. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37928. result.name = name;
  37929. result.id = name;
  37930. return result;
  37931. };
  37932. StandardMaterial.prototype.serialize = function () {
  37933. return BABYLON.SerializationHelper.Serialize(this);
  37934. };
  37935. // Statics
  37936. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37937. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37938. };
  37939. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37940. get: function () {
  37941. return StandardMaterial._DiffuseTextureEnabled;
  37942. },
  37943. set: function (value) {
  37944. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37945. return;
  37946. }
  37947. StandardMaterial._DiffuseTextureEnabled = value;
  37948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37949. },
  37950. enumerable: true,
  37951. configurable: true
  37952. });
  37953. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37954. get: function () {
  37955. return StandardMaterial._AmbientTextureEnabled;
  37956. },
  37957. set: function (value) {
  37958. if (StandardMaterial._AmbientTextureEnabled === value) {
  37959. return;
  37960. }
  37961. StandardMaterial._AmbientTextureEnabled = value;
  37962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37963. },
  37964. enumerable: true,
  37965. configurable: true
  37966. });
  37967. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37968. get: function () {
  37969. return StandardMaterial._OpacityTextureEnabled;
  37970. },
  37971. set: function (value) {
  37972. if (StandardMaterial._OpacityTextureEnabled === value) {
  37973. return;
  37974. }
  37975. StandardMaterial._OpacityTextureEnabled = value;
  37976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37977. },
  37978. enumerable: true,
  37979. configurable: true
  37980. });
  37981. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37982. get: function () {
  37983. return StandardMaterial._ReflectionTextureEnabled;
  37984. },
  37985. set: function (value) {
  37986. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37987. return;
  37988. }
  37989. StandardMaterial._ReflectionTextureEnabled = value;
  37990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37991. },
  37992. enumerable: true,
  37993. configurable: true
  37994. });
  37995. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37996. get: function () {
  37997. return StandardMaterial._EmissiveTextureEnabled;
  37998. },
  37999. set: function (value) {
  38000. if (StandardMaterial._EmissiveTextureEnabled === value) {
  38001. return;
  38002. }
  38003. StandardMaterial._EmissiveTextureEnabled = value;
  38004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38005. },
  38006. enumerable: true,
  38007. configurable: true
  38008. });
  38009. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  38010. get: function () {
  38011. return StandardMaterial._SpecularTextureEnabled;
  38012. },
  38013. set: function (value) {
  38014. if (StandardMaterial._SpecularTextureEnabled === value) {
  38015. return;
  38016. }
  38017. StandardMaterial._SpecularTextureEnabled = value;
  38018. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38019. },
  38020. enumerable: true,
  38021. configurable: true
  38022. });
  38023. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  38024. get: function () {
  38025. return StandardMaterial._BumpTextureEnabled;
  38026. },
  38027. set: function (value) {
  38028. if (StandardMaterial._BumpTextureEnabled === value) {
  38029. return;
  38030. }
  38031. StandardMaterial._BumpTextureEnabled = value;
  38032. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38033. },
  38034. enumerable: true,
  38035. configurable: true
  38036. });
  38037. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  38038. get: function () {
  38039. return StandardMaterial._LightmapTextureEnabled;
  38040. },
  38041. set: function (value) {
  38042. if (StandardMaterial._LightmapTextureEnabled === value) {
  38043. return;
  38044. }
  38045. StandardMaterial._LightmapTextureEnabled = value;
  38046. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38047. },
  38048. enumerable: true,
  38049. configurable: true
  38050. });
  38051. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  38052. get: function () {
  38053. return StandardMaterial._RefractionTextureEnabled;
  38054. },
  38055. set: function (value) {
  38056. if (StandardMaterial._RefractionTextureEnabled === value) {
  38057. return;
  38058. }
  38059. StandardMaterial._RefractionTextureEnabled = value;
  38060. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38061. },
  38062. enumerable: true,
  38063. configurable: true
  38064. });
  38065. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  38066. get: function () {
  38067. return StandardMaterial._ColorGradingTextureEnabled;
  38068. },
  38069. set: function (value) {
  38070. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  38071. return;
  38072. }
  38073. StandardMaterial._ColorGradingTextureEnabled = value;
  38074. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38075. },
  38076. enumerable: true,
  38077. configurable: true
  38078. });
  38079. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  38080. get: function () {
  38081. return StandardMaterial._FresnelEnabled;
  38082. },
  38083. set: function (value) {
  38084. if (StandardMaterial._FresnelEnabled === value) {
  38085. return;
  38086. }
  38087. StandardMaterial._FresnelEnabled = value;
  38088. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  38089. },
  38090. enumerable: true,
  38091. configurable: true
  38092. });
  38093. // Flags used to enable or disable a type of texture for all Standard Materials
  38094. StandardMaterial._DiffuseTextureEnabled = true;
  38095. StandardMaterial._AmbientTextureEnabled = true;
  38096. StandardMaterial._OpacityTextureEnabled = true;
  38097. StandardMaterial._ReflectionTextureEnabled = true;
  38098. StandardMaterial._EmissiveTextureEnabled = true;
  38099. StandardMaterial._SpecularTextureEnabled = true;
  38100. StandardMaterial._BumpTextureEnabled = true;
  38101. StandardMaterial._LightmapTextureEnabled = true;
  38102. StandardMaterial._RefractionTextureEnabled = true;
  38103. StandardMaterial._ColorGradingTextureEnabled = true;
  38104. StandardMaterial._FresnelEnabled = true;
  38105. __decorate([
  38106. BABYLON.serializeAsTexture("diffuseTexture")
  38107. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  38108. __decorate([
  38109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  38110. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  38111. __decorate([
  38112. BABYLON.serializeAsTexture("ambientTexture")
  38113. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  38114. __decorate([
  38115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38116. ], StandardMaterial.prototype, "ambientTexture", void 0);
  38117. __decorate([
  38118. BABYLON.serializeAsTexture("opacityTexture")
  38119. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  38120. __decorate([
  38121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  38122. ], StandardMaterial.prototype, "opacityTexture", void 0);
  38123. __decorate([
  38124. BABYLON.serializeAsTexture("reflectionTexture")
  38125. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  38126. __decorate([
  38127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38128. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  38129. __decorate([
  38130. BABYLON.serializeAsTexture("emissiveTexture")
  38131. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  38132. __decorate([
  38133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38134. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  38135. __decorate([
  38136. BABYLON.serializeAsTexture("specularTexture")
  38137. ], StandardMaterial.prototype, "_specularTexture", void 0);
  38138. __decorate([
  38139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38140. ], StandardMaterial.prototype, "specularTexture", void 0);
  38141. __decorate([
  38142. BABYLON.serializeAsTexture("bumpTexture")
  38143. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  38144. __decorate([
  38145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38146. ], StandardMaterial.prototype, "bumpTexture", void 0);
  38147. __decorate([
  38148. BABYLON.serializeAsTexture("lightmapTexture")
  38149. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  38150. __decorate([
  38151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38152. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  38153. __decorate([
  38154. BABYLON.serializeAsTexture("refractionTexture")
  38155. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  38156. __decorate([
  38157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38158. ], StandardMaterial.prototype, "refractionTexture", void 0);
  38159. __decorate([
  38160. BABYLON.serializeAsColor3("ambient")
  38161. ], StandardMaterial.prototype, "ambientColor", void 0);
  38162. __decorate([
  38163. BABYLON.serializeAsColor3("diffuse")
  38164. ], StandardMaterial.prototype, "diffuseColor", void 0);
  38165. __decorate([
  38166. BABYLON.serializeAsColor3("specular")
  38167. ], StandardMaterial.prototype, "specularColor", void 0);
  38168. __decorate([
  38169. BABYLON.serializeAsColor3("emissive")
  38170. ], StandardMaterial.prototype, "emissiveColor", void 0);
  38171. __decorate([
  38172. BABYLON.serialize()
  38173. ], StandardMaterial.prototype, "specularPower", void 0);
  38174. __decorate([
  38175. BABYLON.serialize("useAlphaFromDiffuseTexture")
  38176. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  38177. __decorate([
  38178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38179. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  38180. __decorate([
  38181. BABYLON.serialize("useEmissiveAsIllumination")
  38182. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  38183. __decorate([
  38184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38185. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  38186. __decorate([
  38187. BABYLON.serialize("linkEmissiveWithDiffuse")
  38188. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  38189. __decorate([
  38190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38191. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  38192. __decorate([
  38193. BABYLON.serialize("useSpecularOverAlpha")
  38194. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  38195. __decorate([
  38196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38197. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  38198. __decorate([
  38199. BABYLON.serialize("useReflectionOverAlpha")
  38200. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  38201. __decorate([
  38202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38203. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  38204. __decorate([
  38205. BABYLON.serialize("disableLighting")
  38206. ], StandardMaterial.prototype, "_disableLighting", void 0);
  38207. __decorate([
  38208. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38209. ], StandardMaterial.prototype, "disableLighting", void 0);
  38210. __decorate([
  38211. BABYLON.serialize("useParallax")
  38212. ], StandardMaterial.prototype, "_useParallax", void 0);
  38213. __decorate([
  38214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38215. ], StandardMaterial.prototype, "useParallax", void 0);
  38216. __decorate([
  38217. BABYLON.serialize("useParallaxOcclusion")
  38218. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  38219. __decorate([
  38220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38221. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  38222. __decorate([
  38223. BABYLON.serialize()
  38224. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  38225. __decorate([
  38226. BABYLON.serialize("roughness")
  38227. ], StandardMaterial.prototype, "_roughness", void 0);
  38228. __decorate([
  38229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38230. ], StandardMaterial.prototype, "roughness", void 0);
  38231. __decorate([
  38232. BABYLON.serialize()
  38233. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  38234. __decorate([
  38235. BABYLON.serialize()
  38236. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  38237. __decorate([
  38238. BABYLON.serialize("useLightmapAsShadowmap")
  38239. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  38240. __decorate([
  38241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38242. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38243. __decorate([
  38244. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  38245. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  38246. __decorate([
  38247. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38248. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  38249. __decorate([
  38250. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  38251. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  38252. __decorate([
  38253. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  38254. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  38255. __decorate([
  38256. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  38257. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  38258. __decorate([
  38259. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38260. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  38261. __decorate([
  38262. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  38263. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  38264. __decorate([
  38265. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38266. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  38267. __decorate([
  38268. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  38269. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  38270. __decorate([
  38271. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38272. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  38273. __decorate([
  38274. BABYLON.serialize("useReflectionFresnelFromSpecular")
  38275. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  38276. __decorate([
  38277. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38278. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  38279. __decorate([
  38280. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  38281. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  38282. __decorate([
  38283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38284. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  38285. __decorate([
  38286. BABYLON.serialize("maxSimultaneousLights")
  38287. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  38288. __decorate([
  38289. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38290. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  38291. __decorate([
  38292. BABYLON.serialize("invertNormalMapX")
  38293. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  38294. __decorate([
  38295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38296. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  38297. __decorate([
  38298. BABYLON.serialize("invertNormalMapY")
  38299. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  38300. __decorate([
  38301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38302. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  38303. __decorate([
  38304. BABYLON.serialize("twoSidedLighting")
  38305. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  38306. __decorate([
  38307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38308. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  38309. __decorate([
  38310. BABYLON.serialize()
  38311. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  38312. return StandardMaterial;
  38313. }(BABYLON.PushMaterial));
  38314. BABYLON.StandardMaterial = StandardMaterial;
  38315. })(BABYLON || (BABYLON = {}));
  38316. //# sourceMappingURL=babylon.standardMaterial.js.map
  38317. var BABYLON;
  38318. (function (BABYLON) {
  38319. var PBRMaterialDefines = /** @class */ (function (_super) {
  38320. __extends(PBRMaterialDefines, _super);
  38321. function PBRMaterialDefines() {
  38322. var _this = _super.call(this) || this;
  38323. _this.PBR = true;
  38324. _this.MAINUV1 = false;
  38325. _this.MAINUV2 = false;
  38326. _this.UV1 = false;
  38327. _this.UV2 = false;
  38328. _this.ALBEDO = false;
  38329. _this.ALBEDODIRECTUV = 0;
  38330. _this.VERTEXCOLOR = false;
  38331. _this.AMBIENT = false;
  38332. _this.AMBIENTDIRECTUV = 0;
  38333. _this.AMBIENTINGRAYSCALE = false;
  38334. _this.OPACITY = false;
  38335. _this.VERTEXALPHA = false;
  38336. _this.OPACITYDIRECTUV = 0;
  38337. _this.OPACITYRGB = false;
  38338. _this.ALPHATEST = false;
  38339. _this.DEPTHPREPASS = false;
  38340. _this.ALPHABLEND = false;
  38341. _this.ALPHAFROMALBEDO = false;
  38342. _this.ALPHATESTVALUE = 0.5;
  38343. _this.SPECULAROVERALPHA = false;
  38344. _this.RADIANCEOVERALPHA = false;
  38345. _this.ALPHAFRESNEL = false;
  38346. _this.LINEARALPHAFRESNEL = false;
  38347. _this.PREMULTIPLYALPHA = false;
  38348. _this.EMISSIVE = false;
  38349. _this.EMISSIVEDIRECTUV = 0;
  38350. _this.REFLECTIVITY = false;
  38351. _this.REFLECTIVITYDIRECTUV = 0;
  38352. _this.SPECULARTERM = false;
  38353. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38354. _this.MICROSURFACEAUTOMATIC = false;
  38355. _this.LODBASEDMICROSFURACE = false;
  38356. _this.MICROSURFACEMAP = false;
  38357. _this.MICROSURFACEMAPDIRECTUV = 0;
  38358. _this.METALLICWORKFLOW = false;
  38359. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38360. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38361. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38362. _this.AOSTOREINMETALMAPRED = false;
  38363. _this.ENVIRONMENTBRDF = false;
  38364. _this.NORMAL = false;
  38365. _this.TANGENT = false;
  38366. _this.BUMP = false;
  38367. _this.BUMPDIRECTUV = 0;
  38368. _this.PARALLAX = false;
  38369. _this.PARALLAXOCCLUSION = false;
  38370. _this.NORMALXYSCALE = true;
  38371. _this.LIGHTMAP = false;
  38372. _this.LIGHTMAPDIRECTUV = 0;
  38373. _this.USELIGHTMAPASSHADOWMAP = false;
  38374. _this.REFLECTION = false;
  38375. _this.REFLECTIONMAP_3D = false;
  38376. _this.REFLECTIONMAP_SPHERICAL = false;
  38377. _this.REFLECTIONMAP_PLANAR = false;
  38378. _this.REFLECTIONMAP_CUBIC = false;
  38379. _this.REFLECTIONMAP_PROJECTION = false;
  38380. _this.REFLECTIONMAP_SKYBOX = false;
  38381. _this.REFLECTIONMAP_EXPLICIT = false;
  38382. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38383. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38384. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38385. _this.INVERTCUBICMAP = false;
  38386. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38387. _this.USESPHERICALINVERTEX = false;
  38388. _this.REFLECTIONMAP_OPPOSITEZ = false;
  38389. _this.LODINREFLECTIONALPHA = false;
  38390. _this.GAMMAREFLECTION = false;
  38391. _this.RADIANCEOCCLUSION = false;
  38392. _this.HORIZONOCCLUSION = false;
  38393. _this.REFRACTION = false;
  38394. _this.REFRACTIONMAP_3D = false;
  38395. _this.REFRACTIONMAP_OPPOSITEZ = false;
  38396. _this.LODINREFRACTIONALPHA = false;
  38397. _this.GAMMAREFRACTION = false;
  38398. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38399. _this.INSTANCES = false;
  38400. _this.NUM_BONE_INFLUENCERS = 0;
  38401. _this.BonesPerMesh = 0;
  38402. _this.NONUNIFORMSCALING = false;
  38403. _this.MORPHTARGETS = false;
  38404. _this.MORPHTARGETS_NORMAL = false;
  38405. _this.MORPHTARGETS_TANGENT = false;
  38406. _this.NUM_MORPH_INFLUENCERS = 0;
  38407. _this.IMAGEPROCESSING = false;
  38408. _this.VIGNETTE = false;
  38409. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38410. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38411. _this.TONEMAPPING = false;
  38412. _this.CONTRAST = false;
  38413. _this.COLORCURVES = false;
  38414. _this.COLORGRADING = false;
  38415. _this.COLORGRADING3D = false;
  38416. _this.SAMPLER3DGREENDEPTH = false;
  38417. _this.SAMPLER3DBGRMAP = false;
  38418. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38419. _this.EXPOSURE = false;
  38420. _this.USEPHYSICALLIGHTFALLOFF = false;
  38421. _this.TWOSIDEDLIGHTING = false;
  38422. _this.SHADOWFLOAT = false;
  38423. _this.CLIPPLANE = false;
  38424. _this.POINTSIZE = false;
  38425. _this.FOG = false;
  38426. _this.LOGARITHMICDEPTH = false;
  38427. _this.FORCENORMALFORWARD = false;
  38428. _this.rebuild();
  38429. return _this;
  38430. }
  38431. PBRMaterialDefines.prototype.reset = function () {
  38432. _super.prototype.reset.call(this);
  38433. this.ALPHATESTVALUE = 0.5;
  38434. this.PBR = true;
  38435. };
  38436. return PBRMaterialDefines;
  38437. }(BABYLON.MaterialDefines));
  38438. /**
  38439. * The Physically based material base class of BJS.
  38440. *
  38441. * This offers the main features of a standard PBR material.
  38442. * For more information, please refer to the documentation :
  38443. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38444. */
  38445. var PBRBaseMaterial = /** @class */ (function (_super) {
  38446. __extends(PBRBaseMaterial, _super);
  38447. /**
  38448. * Instantiates a new PBRMaterial instance.
  38449. *
  38450. * @param name The material name
  38451. * @param scene The scene the material will be use in.
  38452. */
  38453. function PBRBaseMaterial(name, scene) {
  38454. var _this = _super.call(this, name, scene) || this;
  38455. /**
  38456. * Intensity of the direct lights e.g. the four lights available in your scene.
  38457. * This impacts both the direct diffuse and specular highlights.
  38458. */
  38459. _this._directIntensity = 1.0;
  38460. /**
  38461. * Intensity of the emissive part of the material.
  38462. * This helps controlling the emissive effect without modifying the emissive color.
  38463. */
  38464. _this._emissiveIntensity = 1.0;
  38465. /**
  38466. * Intensity of the environment e.g. how much the environment will light the object
  38467. * either through harmonics for rough material or through the refelction for shiny ones.
  38468. */
  38469. _this._environmentIntensity = 1.0;
  38470. /**
  38471. * This is a special control allowing the reduction of the specular highlights coming from the
  38472. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38473. */
  38474. _this._specularIntensity = 1.0;
  38475. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38476. /**
  38477. * Debug Control allowing disabling the bump map on this material.
  38478. */
  38479. _this._disableBumpMap = false;
  38480. /**
  38481. * AKA Occlusion Texture Intensity in other nomenclature.
  38482. */
  38483. _this._ambientTextureStrength = 1.0;
  38484. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38485. /**
  38486. * AKA Diffuse Color in other nomenclature.
  38487. */
  38488. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38489. /**
  38490. * AKA Specular Color in other nomenclature.
  38491. */
  38492. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38493. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38494. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38495. /**
  38496. * AKA Glossiness in other nomenclature.
  38497. */
  38498. _this._microSurface = 0.9;
  38499. /**
  38500. * source material index of refraction (IOR)' / 'destination material IOR.
  38501. */
  38502. _this._indexOfRefraction = 0.66;
  38503. /**
  38504. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38505. */
  38506. _this._invertRefractionY = false;
  38507. /**
  38508. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38509. * Materials half opaque for instance using refraction could benefit from this control.
  38510. */
  38511. _this._linkRefractionWithTransparency = false;
  38512. _this._useLightmapAsShadowmap = false;
  38513. /**
  38514. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38515. * makes the reflect vector face the model (under horizon).
  38516. */
  38517. _this._useHorizonOcclusion = true;
  38518. /**
  38519. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38520. * too much the area relying on ambient texture to define their ambient occlusion.
  38521. */
  38522. _this._useRadianceOcclusion = true;
  38523. /**
  38524. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38525. */
  38526. _this._useAlphaFromAlbedoTexture = false;
  38527. /**
  38528. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38529. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38530. */
  38531. _this._useSpecularOverAlpha = true;
  38532. /**
  38533. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38534. */
  38535. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38536. /**
  38537. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38538. */
  38539. _this._useRoughnessFromMetallicTextureAlpha = true;
  38540. /**
  38541. * Specifies if the metallic texture contains the roughness information in its green channel.
  38542. */
  38543. _this._useRoughnessFromMetallicTextureGreen = false;
  38544. /**
  38545. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38546. */
  38547. _this._useMetallnessFromMetallicTextureBlue = false;
  38548. /**
  38549. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38550. */
  38551. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38552. /**
  38553. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38554. */
  38555. _this._useAmbientInGrayScale = false;
  38556. /**
  38557. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38558. * The material will try to infer what glossiness each pixel should be.
  38559. */
  38560. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38561. /**
  38562. * BJS is using an harcoded light falloff based on a manually sets up range.
  38563. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38564. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38565. */
  38566. _this._usePhysicalLightFalloff = true;
  38567. /**
  38568. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38569. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38570. */
  38571. _this._useRadianceOverAlpha = true;
  38572. /**
  38573. * Allows using the bump map in parallax mode.
  38574. */
  38575. _this._useParallax = false;
  38576. /**
  38577. * Allows using the bump map in parallax occlusion mode.
  38578. */
  38579. _this._useParallaxOcclusion = false;
  38580. /**
  38581. * Controls the scale bias of the parallax mode.
  38582. */
  38583. _this._parallaxScaleBias = 0.05;
  38584. /**
  38585. * If sets to true, disables all the lights affecting the material.
  38586. */
  38587. _this._disableLighting = false;
  38588. /**
  38589. * Number of Simultaneous lights allowed on the material.
  38590. */
  38591. _this._maxSimultaneousLights = 4;
  38592. /**
  38593. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38594. */
  38595. _this._invertNormalMapX = false;
  38596. /**
  38597. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38598. */
  38599. _this._invertNormalMapY = false;
  38600. /**
  38601. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38602. */
  38603. _this._twoSidedLighting = false;
  38604. /**
  38605. * Defines the alpha limits in alpha test mode.
  38606. */
  38607. _this._alphaCutOff = 0.4;
  38608. /**
  38609. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38610. */
  38611. _this._forceAlphaTest = false;
  38612. /**
  38613. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38614. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38615. */
  38616. _this._useAlphaFresnel = false;
  38617. /**
  38618. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38619. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38620. */
  38621. _this._useLinearAlphaFresnel = false;
  38622. /**
  38623. * The transparency mode of the material.
  38624. */
  38625. _this._transparencyMode = null;
  38626. /**
  38627. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38628. * from cos thetav and roughness:
  38629. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38630. */
  38631. _this._environmentBRDFTexture = null;
  38632. /**
  38633. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38634. */
  38635. _this._forceIrradianceInFragment = false;
  38636. /**
  38637. * Force normal to face away from face.
  38638. */
  38639. _this._forceNormalForward = false;
  38640. /**
  38641. * Force metallic workflow.
  38642. */
  38643. _this._forceMetallicWorkflow = false;
  38644. _this._renderTargets = new BABYLON.SmartArray(16);
  38645. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38646. // Setup the default processing configuration to the scene.
  38647. _this._attachImageProcessingConfiguration(null);
  38648. _this.getRenderTargetTextures = function () {
  38649. _this._renderTargets.reset();
  38650. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38651. _this._renderTargets.push(_this._reflectionTexture);
  38652. }
  38653. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38654. _this._renderTargets.push(_this._refractionTexture);
  38655. }
  38656. return _this._renderTargets;
  38657. };
  38658. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38659. return _this;
  38660. }
  38661. /**
  38662. * Attaches a new image processing configuration to the PBR Material.
  38663. * @param configuration
  38664. */
  38665. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38666. var _this = this;
  38667. if (configuration === this._imageProcessingConfiguration) {
  38668. return;
  38669. }
  38670. // Detaches observer.
  38671. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38672. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38673. }
  38674. // Pick the scene configuration if needed.
  38675. if (!configuration) {
  38676. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38677. }
  38678. else {
  38679. this._imageProcessingConfiguration = configuration;
  38680. }
  38681. // Attaches observer.
  38682. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38683. _this._markAllSubMeshesAsImageProcessingDirty();
  38684. });
  38685. };
  38686. PBRBaseMaterial.prototype.getClassName = function () {
  38687. return "PBRBaseMaterial";
  38688. };
  38689. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38690. get: function () {
  38691. return this._useLogarithmicDepth;
  38692. },
  38693. set: function (value) {
  38694. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38695. },
  38696. enumerable: true,
  38697. configurable: true
  38698. });
  38699. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38700. /**
  38701. * Gets the current transparency mode.
  38702. */
  38703. get: function () {
  38704. return this._transparencyMode;
  38705. },
  38706. /**
  38707. * Sets the transparency mode of the material.
  38708. */
  38709. set: function (value) {
  38710. if (this._transparencyMode === value) {
  38711. return;
  38712. }
  38713. this._transparencyMode = value;
  38714. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38715. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38716. },
  38717. enumerable: true,
  38718. configurable: true
  38719. });
  38720. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38721. /**
  38722. * Returns true if alpha blending should be disabled.
  38723. */
  38724. get: function () {
  38725. return (this._linkRefractionWithTransparency ||
  38726. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38727. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38728. },
  38729. enumerable: true,
  38730. configurable: true
  38731. });
  38732. /**
  38733. * Specifies whether or not this material should be rendered in alpha blend mode.
  38734. */
  38735. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38736. if (this._disableAlphaBlending) {
  38737. return false;
  38738. }
  38739. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38740. };
  38741. /**
  38742. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38743. */
  38744. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38745. if (this._disableAlphaBlending) {
  38746. return false;
  38747. }
  38748. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38749. };
  38750. /**
  38751. * Specifies whether or not this material should be rendered in alpha test mode.
  38752. */
  38753. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38754. if (this._forceAlphaTest) {
  38755. return true;
  38756. }
  38757. if (this._linkRefractionWithTransparency) {
  38758. return false;
  38759. }
  38760. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38761. };
  38762. /**
  38763. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38764. */
  38765. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38766. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38767. };
  38768. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38769. return this._albedoTexture;
  38770. };
  38771. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38772. var _this = this;
  38773. if (subMesh.effect && this.isFrozen) {
  38774. if (this._wasPreviouslyReady) {
  38775. return true;
  38776. }
  38777. }
  38778. if (!subMesh._materialDefines) {
  38779. subMesh._materialDefines = new PBRMaterialDefines();
  38780. }
  38781. var scene = this.getScene();
  38782. var defines = subMesh._materialDefines;
  38783. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38784. if (defines._renderId === scene.getRenderId()) {
  38785. return true;
  38786. }
  38787. }
  38788. var engine = scene.getEngine();
  38789. // Lights
  38790. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38791. defines._needNormals = true;
  38792. // Textures
  38793. if (defines._areTexturesDirty) {
  38794. defines._needUVs = false;
  38795. if (scene.texturesEnabled) {
  38796. if (scene.getEngine().getCaps().textureLOD) {
  38797. defines.LODBASEDMICROSFURACE = true;
  38798. }
  38799. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38800. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38801. return false;
  38802. }
  38803. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38804. }
  38805. else {
  38806. defines.ALBEDO = false;
  38807. }
  38808. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38809. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38810. return false;
  38811. }
  38812. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38813. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38814. }
  38815. else {
  38816. defines.AMBIENT = false;
  38817. }
  38818. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38819. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38820. return false;
  38821. }
  38822. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38823. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38824. }
  38825. else {
  38826. defines.OPACITY = false;
  38827. }
  38828. var reflectionTexture = this._getReflectionTexture();
  38829. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38830. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38831. return false;
  38832. }
  38833. defines.REFLECTION = true;
  38834. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38835. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38836. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38837. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38838. defines.INVERTCUBICMAP = true;
  38839. }
  38840. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38841. switch (reflectionTexture.coordinatesMode) {
  38842. case BABYLON.Texture.CUBIC_MODE:
  38843. case BABYLON.Texture.INVCUBIC_MODE:
  38844. defines.REFLECTIONMAP_CUBIC = true;
  38845. break;
  38846. case BABYLON.Texture.EXPLICIT_MODE:
  38847. defines.REFLECTIONMAP_EXPLICIT = true;
  38848. break;
  38849. case BABYLON.Texture.PLANAR_MODE:
  38850. defines.REFLECTIONMAP_PLANAR = true;
  38851. break;
  38852. case BABYLON.Texture.PROJECTION_MODE:
  38853. defines.REFLECTIONMAP_PROJECTION = true;
  38854. break;
  38855. case BABYLON.Texture.SKYBOX_MODE:
  38856. defines.REFLECTIONMAP_SKYBOX = true;
  38857. break;
  38858. case BABYLON.Texture.SPHERICAL_MODE:
  38859. defines.REFLECTIONMAP_SPHERICAL = true;
  38860. break;
  38861. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38862. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38863. break;
  38864. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38865. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38866. break;
  38867. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38868. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38869. break;
  38870. }
  38871. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38872. if (reflectionTexture.sphericalPolynomial) {
  38873. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38874. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38875. defines.USESPHERICALINVERTEX = false;
  38876. }
  38877. else {
  38878. defines.USESPHERICALINVERTEX = true;
  38879. }
  38880. }
  38881. }
  38882. }
  38883. else {
  38884. defines.REFLECTION = false;
  38885. defines.REFLECTIONMAP_3D = false;
  38886. defines.REFLECTIONMAP_SPHERICAL = false;
  38887. defines.REFLECTIONMAP_PLANAR = false;
  38888. defines.REFLECTIONMAP_CUBIC = false;
  38889. defines.REFLECTIONMAP_PROJECTION = false;
  38890. defines.REFLECTIONMAP_SKYBOX = false;
  38891. defines.REFLECTIONMAP_EXPLICIT = false;
  38892. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38893. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38894. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38895. defines.INVERTCUBICMAP = false;
  38896. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38897. defines.USESPHERICALINVERTEX = false;
  38898. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38899. defines.LODINREFLECTIONALPHA = false;
  38900. defines.GAMMAREFLECTION = false;
  38901. }
  38902. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38903. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38904. return false;
  38905. }
  38906. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38907. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38908. }
  38909. else {
  38910. defines.LIGHTMAP = false;
  38911. }
  38912. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38913. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38914. return false;
  38915. }
  38916. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38917. }
  38918. else {
  38919. defines.EMISSIVE = false;
  38920. }
  38921. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38922. if (this._metallicTexture) {
  38923. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38924. return false;
  38925. }
  38926. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38927. defines.METALLICWORKFLOW = true;
  38928. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38929. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38930. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38931. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38932. }
  38933. else if (this._reflectivityTexture) {
  38934. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38935. return false;
  38936. }
  38937. defines.METALLICWORKFLOW = false;
  38938. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38939. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38940. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38941. }
  38942. else {
  38943. defines.METALLICWORKFLOW = false;
  38944. defines.REFLECTIVITY = false;
  38945. }
  38946. if (this._microSurfaceTexture) {
  38947. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38948. return false;
  38949. }
  38950. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38951. }
  38952. else {
  38953. defines.MICROSURFACEMAP = false;
  38954. }
  38955. }
  38956. else {
  38957. defines.REFLECTIVITY = false;
  38958. defines.MICROSURFACEMAP = false;
  38959. }
  38960. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38961. // Bump texure can not be none blocking.
  38962. if (!this._bumpTexture.isReady()) {
  38963. return false;
  38964. }
  38965. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38966. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38967. defines.PARALLAX = true;
  38968. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38969. }
  38970. else {
  38971. defines.PARALLAX = false;
  38972. }
  38973. }
  38974. else {
  38975. defines.BUMP = false;
  38976. }
  38977. var refractionTexture = this._getRefractionTexture();
  38978. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38979. if (!refractionTexture.isReadyOrNotBlocking()) {
  38980. return false;
  38981. }
  38982. defines.REFRACTION = true;
  38983. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38984. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38985. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38986. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38987. if (this._linkRefractionWithTransparency) {
  38988. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38989. }
  38990. }
  38991. else {
  38992. defines.REFRACTION = false;
  38993. }
  38994. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38995. // This is blocking.
  38996. if (!this._environmentBRDFTexture.isReady()) {
  38997. return false;
  38998. }
  38999. defines.ENVIRONMENTBRDF = true;
  39000. }
  39001. else {
  39002. defines.ENVIRONMENTBRDF = false;
  39003. }
  39004. if (this._shouldUseAlphaFromAlbedoTexture()) {
  39005. defines.ALPHAFROMALBEDO = true;
  39006. }
  39007. else {
  39008. defines.ALPHAFROMALBEDO = false;
  39009. }
  39010. }
  39011. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39012. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  39013. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  39014. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  39015. defines.METALLICWORKFLOW = true;
  39016. }
  39017. else {
  39018. defines.METALLICWORKFLOW = false;
  39019. }
  39020. if (!this.backFaceCulling && this._twoSidedLighting) {
  39021. defines.TWOSIDEDLIGHTING = true;
  39022. }
  39023. else {
  39024. defines.TWOSIDEDLIGHTING = false;
  39025. }
  39026. defines.ALPHATESTVALUE = this._alphaCutOff;
  39027. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39028. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  39029. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  39030. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  39031. }
  39032. if (defines._areImageProcessingDirty) {
  39033. if (!this._imageProcessingConfiguration.isReady()) {
  39034. return false;
  39035. }
  39036. this._imageProcessingConfiguration.prepareDefines(defines);
  39037. }
  39038. defines.FORCENORMALFORWARD = this._forceNormalForward;
  39039. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  39040. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  39041. // Misc.
  39042. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  39043. // Values that need to be evaluated on every frame
  39044. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  39045. // Attribs
  39046. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  39047. var bufferMesh = null;
  39048. if (mesh instanceof BABYLON.InstancedMesh) {
  39049. bufferMesh = mesh.sourceMesh;
  39050. }
  39051. else if (mesh instanceof BABYLON.Mesh) {
  39052. bufferMesh = mesh;
  39053. }
  39054. if (bufferMesh) {
  39055. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39056. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  39057. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  39058. var normals = normalVertexBuffer.getData();
  39059. var vertexBufferOffset = normalVertexBuffer.getOffset();
  39060. var strideSize = normalVertexBuffer.getStrideSize();
  39061. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  39062. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  39063. defines.NORMAL = false;
  39064. }
  39065. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39066. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  39067. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  39068. var tangents = tangentVertexBuffer.getData();
  39069. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  39070. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  39071. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  39072. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  39073. defines.TANGENT = false;
  39074. }
  39075. }
  39076. }
  39077. else {
  39078. if (!scene.getEngine().getCaps().standardDerivatives) {
  39079. bufferMesh.createNormals(true);
  39080. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  39081. }
  39082. }
  39083. }
  39084. }
  39085. // Get correct effect
  39086. if (defines.isDirty) {
  39087. defines.markAsProcessed();
  39088. scene.resetCachedMaterial();
  39089. // Fallbacks
  39090. var fallbacks = new BABYLON.EffectFallbacks();
  39091. var fallbackRank = 0;
  39092. if (defines.USESPHERICALINVERTEX) {
  39093. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  39094. }
  39095. if (defines.FOG) {
  39096. fallbacks.addFallback(fallbackRank, "FOG");
  39097. }
  39098. if (defines.POINTSIZE) {
  39099. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  39100. }
  39101. if (defines.LOGARITHMICDEPTH) {
  39102. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  39103. }
  39104. if (defines.PARALLAX) {
  39105. fallbacks.addFallback(fallbackRank, "PARALLAX");
  39106. }
  39107. if (defines.PARALLAXOCCLUSION) {
  39108. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  39109. }
  39110. if (defines.ENVIRONMENTBRDF) {
  39111. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  39112. }
  39113. if (defines.TANGENT) {
  39114. fallbacks.addFallback(fallbackRank++, "TANGENT");
  39115. }
  39116. if (defines.BUMP) {
  39117. fallbacks.addFallback(fallbackRank++, "BUMP");
  39118. }
  39119. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  39120. if (defines.SPECULARTERM) {
  39121. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  39122. }
  39123. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  39124. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  39125. }
  39126. if (defines.LIGHTMAP) {
  39127. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  39128. }
  39129. if (defines.NORMAL) {
  39130. fallbacks.addFallback(fallbackRank++, "NORMAL");
  39131. }
  39132. if (defines.AMBIENT) {
  39133. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  39134. }
  39135. if (defines.EMISSIVE) {
  39136. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  39137. }
  39138. if (defines.VERTEXCOLOR) {
  39139. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  39140. }
  39141. if (defines.NUM_BONE_INFLUENCERS > 0) {
  39142. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  39143. }
  39144. if (defines.MORPHTARGETS) {
  39145. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  39146. }
  39147. //Attributes
  39148. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39149. if (defines.NORMAL) {
  39150. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39151. }
  39152. if (defines.TANGENT) {
  39153. attribs.push(BABYLON.VertexBuffer.TangentKind);
  39154. }
  39155. if (defines.UV1) {
  39156. attribs.push(BABYLON.VertexBuffer.UVKind);
  39157. }
  39158. if (defines.UV2) {
  39159. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39160. }
  39161. if (defines.VERTEXCOLOR) {
  39162. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39163. }
  39164. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39165. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39166. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39167. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39168. "vFogInfos", "vFogColor", "pointSize",
  39169. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39170. "mBones",
  39171. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39172. "vLightingIntensity",
  39173. "logarithmicDepthConstant",
  39174. "vSphericalX", "vSphericalY", "vSphericalZ",
  39175. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39176. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39177. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  39178. "vTangentSpaceParams"
  39179. ];
  39180. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  39181. "bumpSampler", "lightmapSampler", "opacitySampler",
  39182. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  39183. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  39184. "microSurfaceSampler", "environmentBrdfSampler"];
  39185. var uniformBuffers = ["Material", "Scene"];
  39186. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39187. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39188. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39189. uniformsNames: uniforms,
  39190. uniformBuffersNames: uniformBuffers,
  39191. samplers: samplers,
  39192. defines: defines,
  39193. maxSimultaneousLights: this._maxSimultaneousLights
  39194. });
  39195. var onCompiled = function (effect) {
  39196. if (_this.onCompiled) {
  39197. _this.onCompiled(effect);
  39198. }
  39199. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39200. };
  39201. var join = defines.toString();
  39202. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39203. attributes: attribs,
  39204. uniformsNames: uniforms,
  39205. uniformBuffersNames: uniformBuffers,
  39206. samplers: samplers,
  39207. defines: join,
  39208. fallbacks: fallbacks,
  39209. onCompiled: onCompiled,
  39210. onError: this.onError,
  39211. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39212. }, engine), defines);
  39213. this.buildUniformLayout();
  39214. }
  39215. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39216. return false;
  39217. }
  39218. defines._renderId = scene.getRenderId();
  39219. this._wasPreviouslyReady = true;
  39220. return true;
  39221. };
  39222. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39223. // Order is important !
  39224. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39225. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39226. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39227. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39228. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39229. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39230. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39231. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39232. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39233. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39234. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39235. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39236. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39237. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39238. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39239. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39240. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39241. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39242. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39243. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39244. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39245. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39246. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39247. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39248. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  39249. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  39250. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39251. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39252. this._uniformBuffer.addUniform("pointSize", 1);
  39253. this._uniformBuffer.create();
  39254. };
  39255. PBRBaseMaterial.prototype.unbind = function () {
  39256. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39257. this._uniformBuffer.setTexture("reflectionSampler", null);
  39258. }
  39259. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39260. this._uniformBuffer.setTexture("refractionSampler", null);
  39261. }
  39262. _super.prototype.unbind.call(this);
  39263. };
  39264. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39265. this._activeEffect.setMatrix("world", world);
  39266. };
  39267. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39268. var scene = this.getScene();
  39269. var defines = subMesh._materialDefines;
  39270. if (!defines) {
  39271. return;
  39272. }
  39273. var effect = subMesh.effect;
  39274. if (!effect) {
  39275. return;
  39276. }
  39277. this._activeEffect = effect;
  39278. // Matrices
  39279. this.bindOnlyWorldMatrix(world);
  39280. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39281. // Bones
  39282. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39283. var reflectionTexture = null;
  39284. if (mustRebind) {
  39285. this._uniformBuffer.bindToEffect(effect, "Material");
  39286. this.bindViewProjection(effect);
  39287. reflectionTexture = this._getReflectionTexture();
  39288. var refractionTexture = this._getRefractionTexture();
  39289. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39290. // Texture uniforms
  39291. if (scene.texturesEnabled) {
  39292. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39293. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39294. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  39295. }
  39296. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39297. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39298. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39299. }
  39300. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39301. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39302. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39303. }
  39304. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39305. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39306. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39307. var polynomials = reflectionTexture.sphericalPolynomial;
  39308. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  39309. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  39310. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  39311. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  39312. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  39313. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  39314. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  39315. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  39316. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  39317. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  39318. }
  39319. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  39320. }
  39321. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39322. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39323. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39324. }
  39325. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39326. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39327. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39328. }
  39329. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39330. if (this._metallicTexture) {
  39331. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39332. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  39333. }
  39334. else if (this._reflectivityTexture) {
  39335. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39336. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  39337. }
  39338. if (this._microSurfaceTexture) {
  39339. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39340. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  39341. }
  39342. }
  39343. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39344. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39345. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39346. if (scene._mirroredCameraPosition) {
  39347. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39348. }
  39349. else {
  39350. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39351. }
  39352. }
  39353. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39354. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  39355. var depth = 1.0;
  39356. if (!refractionTexture.isCube) {
  39357. if (refractionTexture.depth) {
  39358. depth = refractionTexture.depth;
  39359. }
  39360. }
  39361. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39362. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  39363. }
  39364. }
  39365. // Point size
  39366. if (this.pointsCloud) {
  39367. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39368. }
  39369. // Colors
  39370. if (defines.METALLICWORKFLOW) {
  39371. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39372. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39373. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39374. }
  39375. else {
  39376. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  39377. }
  39378. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  39379. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  39380. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  39381. // Misc
  39382. this._lightingInfos.x = this._directIntensity;
  39383. this._lightingInfos.y = this._emissiveIntensity;
  39384. this._lightingInfos.z = this._environmentIntensity;
  39385. this._lightingInfos.w = this._specularIntensity;
  39386. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39387. }
  39388. // Textures
  39389. if (scene.texturesEnabled) {
  39390. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39391. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39392. }
  39393. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39394. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39395. }
  39396. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39397. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39398. }
  39399. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39400. if (defines.LODBASEDMICROSFURACE) {
  39401. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  39402. }
  39403. else {
  39404. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  39405. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  39406. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  39407. }
  39408. }
  39409. if (defines.ENVIRONMENTBRDF) {
  39410. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  39411. }
  39412. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39413. if (defines.LODBASEDMICROSFURACE) {
  39414. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39415. }
  39416. else {
  39417. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39418. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39419. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39420. }
  39421. }
  39422. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39423. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39424. }
  39425. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39426. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39427. }
  39428. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39429. if (this._metallicTexture) {
  39430. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39431. }
  39432. else if (this._reflectivityTexture) {
  39433. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39434. }
  39435. if (this._microSurfaceTexture) {
  39436. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39437. }
  39438. }
  39439. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39440. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39441. }
  39442. }
  39443. // Clip plane
  39444. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39445. // Colors
  39446. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39447. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39448. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39449. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39450. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39451. }
  39452. if (mustRebind || !this.isFrozen) {
  39453. // Lights
  39454. if (scene.lightsEnabled && !this._disableLighting) {
  39455. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39456. }
  39457. // View
  39458. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39459. this.bindView(effect);
  39460. }
  39461. // Fog
  39462. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39463. // Morph targets
  39464. if (defines.NUM_MORPH_INFLUENCERS) {
  39465. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39466. }
  39467. // image processing
  39468. this._imageProcessingConfiguration.bind(this._activeEffect);
  39469. // Log. depth
  39470. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39471. }
  39472. this._uniformBuffer.update();
  39473. this._afterBind(mesh);
  39474. };
  39475. PBRBaseMaterial.prototype.getAnimatables = function () {
  39476. var results = [];
  39477. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39478. results.push(this._albedoTexture);
  39479. }
  39480. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39481. results.push(this._ambientTexture);
  39482. }
  39483. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39484. results.push(this._opacityTexture);
  39485. }
  39486. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39487. results.push(this._reflectionTexture);
  39488. }
  39489. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39490. results.push(this._emissiveTexture);
  39491. }
  39492. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39493. results.push(this._metallicTexture);
  39494. }
  39495. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39496. results.push(this._reflectivityTexture);
  39497. }
  39498. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39499. results.push(this._bumpTexture);
  39500. }
  39501. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39502. results.push(this._lightmapTexture);
  39503. }
  39504. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39505. results.push(this._refractionTexture);
  39506. }
  39507. return results;
  39508. };
  39509. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39510. if (this._reflectionTexture) {
  39511. return this._reflectionTexture;
  39512. }
  39513. return this.getScene().environmentTexture;
  39514. };
  39515. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39516. if (this._refractionTexture) {
  39517. return this._refractionTexture;
  39518. }
  39519. if (this._linkRefractionWithTransparency) {
  39520. return this.getScene().environmentTexture;
  39521. }
  39522. return null;
  39523. };
  39524. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39525. if (forceDisposeTextures) {
  39526. if (this._albedoTexture) {
  39527. this._albedoTexture.dispose();
  39528. }
  39529. if (this._ambientTexture) {
  39530. this._ambientTexture.dispose();
  39531. }
  39532. if (this._opacityTexture) {
  39533. this._opacityTexture.dispose();
  39534. }
  39535. if (this._reflectionTexture) {
  39536. this._reflectionTexture.dispose();
  39537. }
  39538. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39539. this._environmentBRDFTexture.dispose();
  39540. }
  39541. if (this._emissiveTexture) {
  39542. this._emissiveTexture.dispose();
  39543. }
  39544. if (this._metallicTexture) {
  39545. this._metallicTexture.dispose();
  39546. }
  39547. if (this._reflectivityTexture) {
  39548. this._reflectivityTexture.dispose();
  39549. }
  39550. if (this._bumpTexture) {
  39551. this._bumpTexture.dispose();
  39552. }
  39553. if (this._lightmapTexture) {
  39554. this._lightmapTexture.dispose();
  39555. }
  39556. if (this._refractionTexture) {
  39557. this._refractionTexture.dispose();
  39558. }
  39559. }
  39560. this._renderTargets.dispose();
  39561. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39562. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39563. }
  39564. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39565. };
  39566. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39567. __decorate([
  39568. BABYLON.serializeAsImageProcessingConfiguration()
  39569. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39570. __decorate([
  39571. BABYLON.serialize()
  39572. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39573. __decorate([
  39574. BABYLON.serialize()
  39575. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39576. return PBRBaseMaterial;
  39577. }(BABYLON.PushMaterial));
  39578. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39579. })(BABYLON || (BABYLON = {}));
  39580. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39581. var BABYLON;
  39582. (function (BABYLON) {
  39583. /**
  39584. * The Physically based simple base material of BJS.
  39585. *
  39586. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39587. * It is used as the base class for both the specGloss and metalRough conventions.
  39588. */
  39589. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39590. __extends(PBRBaseSimpleMaterial, _super);
  39591. /**
  39592. * Instantiates a new PBRMaterial instance.
  39593. *
  39594. * @param name The material name
  39595. * @param scene The scene the material will be use in.
  39596. */
  39597. function PBRBaseSimpleMaterial(name, scene) {
  39598. var _this = _super.call(this, name, scene) || this;
  39599. /**
  39600. * Number of Simultaneous lights allowed on the material.
  39601. */
  39602. _this.maxSimultaneousLights = 4;
  39603. /**
  39604. * If sets to true, disables all the lights affecting the material.
  39605. */
  39606. _this.disableLighting = false;
  39607. /**
  39608. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39609. */
  39610. _this.invertNormalMapX = false;
  39611. /**
  39612. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39613. */
  39614. _this.invertNormalMapY = false;
  39615. /**
  39616. * Emissivie color used to self-illuminate the model.
  39617. */
  39618. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39619. /**
  39620. * Occlusion Channel Strenght.
  39621. */
  39622. _this.occlusionStrength = 1.0;
  39623. _this.useLightmapAsShadowmap = false;
  39624. _this._useAlphaFromAlbedoTexture = true;
  39625. _this._useAmbientInGrayScale = true;
  39626. return _this;
  39627. }
  39628. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39629. /**
  39630. * Gets the current double sided mode.
  39631. */
  39632. get: function () {
  39633. return this._twoSidedLighting;
  39634. },
  39635. /**
  39636. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39637. */
  39638. set: function (value) {
  39639. if (this._twoSidedLighting === value) {
  39640. return;
  39641. }
  39642. this._twoSidedLighting = value;
  39643. this.backFaceCulling = !value;
  39644. this._markAllSubMeshesAsTexturesDirty();
  39645. },
  39646. enumerable: true,
  39647. configurable: true
  39648. });
  39649. /**
  39650. * Return the active textures of the material.
  39651. */
  39652. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39653. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39654. if (this.environmentTexture) {
  39655. activeTextures.push(this.environmentTexture);
  39656. }
  39657. if (this.normalTexture) {
  39658. activeTextures.push(this.normalTexture);
  39659. }
  39660. if (this.emissiveTexture) {
  39661. activeTextures.push(this.emissiveTexture);
  39662. }
  39663. if (this.occlusionTexture) {
  39664. activeTextures.push(this.occlusionTexture);
  39665. }
  39666. if (this.lightmapTexture) {
  39667. activeTextures.push(this.lightmapTexture);
  39668. }
  39669. return activeTextures;
  39670. };
  39671. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39672. if (_super.prototype.hasTexture.call(this, texture)) {
  39673. return true;
  39674. }
  39675. if (this.lightmapTexture === texture) {
  39676. return true;
  39677. }
  39678. return false;
  39679. };
  39680. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39681. return "PBRBaseSimpleMaterial";
  39682. };
  39683. __decorate([
  39684. BABYLON.serialize(),
  39685. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39686. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39687. __decorate([
  39688. BABYLON.serialize(),
  39689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39690. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39691. __decorate([
  39692. BABYLON.serializeAsTexture(),
  39693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39694. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39695. __decorate([
  39696. BABYLON.serialize(),
  39697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39698. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39699. __decorate([
  39700. BABYLON.serialize(),
  39701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39702. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39703. __decorate([
  39704. BABYLON.serializeAsTexture(),
  39705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39706. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39707. __decorate([
  39708. BABYLON.serializeAsColor3("emissive"),
  39709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39710. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39711. __decorate([
  39712. BABYLON.serializeAsTexture(),
  39713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39714. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39715. __decorate([
  39716. BABYLON.serialize(),
  39717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39718. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39719. __decorate([
  39720. BABYLON.serializeAsTexture(),
  39721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39722. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39723. __decorate([
  39724. BABYLON.serialize(),
  39725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39726. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39727. __decorate([
  39728. BABYLON.serialize()
  39729. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39730. __decorate([
  39731. BABYLON.serializeAsTexture(),
  39732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39733. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39734. __decorate([
  39735. BABYLON.serialize(),
  39736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39737. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39738. return PBRBaseSimpleMaterial;
  39739. }(BABYLON.PBRBaseMaterial));
  39740. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39741. })(BABYLON || (BABYLON = {}));
  39742. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39743. var BABYLON;
  39744. (function (BABYLON) {
  39745. /**
  39746. * The Physically based material of BJS.
  39747. *
  39748. * This offers the main features of a standard PBR material.
  39749. * For more information, please refer to the documentation :
  39750. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39751. */
  39752. var PBRMaterial = /** @class */ (function (_super) {
  39753. __extends(PBRMaterial, _super);
  39754. /**
  39755. * Instantiates a new PBRMaterial instance.
  39756. *
  39757. * @param name The material name
  39758. * @param scene The scene the material will be use in.
  39759. */
  39760. function PBRMaterial(name, scene) {
  39761. var _this = _super.call(this, name, scene) || this;
  39762. /**
  39763. * Intensity of the direct lights e.g. the four lights available in your scene.
  39764. * This impacts both the direct diffuse and specular highlights.
  39765. */
  39766. _this.directIntensity = 1.0;
  39767. /**
  39768. * Intensity of the emissive part of the material.
  39769. * This helps controlling the emissive effect without modifying the emissive color.
  39770. */
  39771. _this.emissiveIntensity = 1.0;
  39772. /**
  39773. * Intensity of the environment e.g. how much the environment will light the object
  39774. * either through harmonics for rough material or through the refelction for shiny ones.
  39775. */
  39776. _this.environmentIntensity = 1.0;
  39777. /**
  39778. * This is a special control allowing the reduction of the specular highlights coming from the
  39779. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39780. */
  39781. _this.specularIntensity = 1.0;
  39782. /**
  39783. * Debug Control allowing disabling the bump map on this material.
  39784. */
  39785. _this.disableBumpMap = false;
  39786. /**
  39787. * AKA Occlusion Texture Intensity in other nomenclature.
  39788. */
  39789. _this.ambientTextureStrength = 1.0;
  39790. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39791. /**
  39792. * AKA Diffuse Color in other nomenclature.
  39793. */
  39794. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39795. /**
  39796. * AKA Specular Color in other nomenclature.
  39797. */
  39798. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39799. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39800. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39801. /**
  39802. * AKA Glossiness in other nomenclature.
  39803. */
  39804. _this.microSurface = 1.0;
  39805. /**
  39806. * source material index of refraction (IOR)' / 'destination material IOR.
  39807. */
  39808. _this.indexOfRefraction = 0.66;
  39809. /**
  39810. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39811. */
  39812. _this.invertRefractionY = false;
  39813. /**
  39814. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39815. * Materials half opaque for instance using refraction could benefit from this control.
  39816. */
  39817. _this.linkRefractionWithTransparency = false;
  39818. _this.useLightmapAsShadowmap = false;
  39819. /**
  39820. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39821. */
  39822. _this.useAlphaFromAlbedoTexture = false;
  39823. /**
  39824. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39825. */
  39826. _this.forceAlphaTest = false;
  39827. /**
  39828. * Defines the alpha limits in alpha test mode.
  39829. */
  39830. _this.alphaCutOff = 0.4;
  39831. /**
  39832. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39833. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39834. */
  39835. _this.useSpecularOverAlpha = true;
  39836. /**
  39837. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39838. */
  39839. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39840. /**
  39841. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39842. */
  39843. _this.useRoughnessFromMetallicTextureAlpha = true;
  39844. /**
  39845. * Specifies if the metallic texture contains the roughness information in its green channel.
  39846. */
  39847. _this.useRoughnessFromMetallicTextureGreen = false;
  39848. /**
  39849. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39850. */
  39851. _this.useMetallnessFromMetallicTextureBlue = false;
  39852. /**
  39853. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39854. */
  39855. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39856. /**
  39857. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39858. */
  39859. _this.useAmbientInGrayScale = false;
  39860. /**
  39861. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39862. * The material will try to infer what glossiness each pixel should be.
  39863. */
  39864. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39865. /**
  39866. * BJS is using an harcoded light falloff based on a manually sets up range.
  39867. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39868. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39869. */
  39870. _this.usePhysicalLightFalloff = true;
  39871. /**
  39872. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39873. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39874. */
  39875. _this.useRadianceOverAlpha = true;
  39876. /**
  39877. * Allows using the bump map in parallax mode.
  39878. */
  39879. _this.useParallax = false;
  39880. /**
  39881. * Allows using the bump map in parallax occlusion mode.
  39882. */
  39883. _this.useParallaxOcclusion = false;
  39884. /**
  39885. * Controls the scale bias of the parallax mode.
  39886. */
  39887. _this.parallaxScaleBias = 0.05;
  39888. /**
  39889. * If sets to true, disables all the lights affecting the material.
  39890. */
  39891. _this.disableLighting = false;
  39892. /**
  39893. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39894. */
  39895. _this.forceIrradianceInFragment = false;
  39896. /**
  39897. * Number of Simultaneous lights allowed on the material.
  39898. */
  39899. _this.maxSimultaneousLights = 4;
  39900. /**
  39901. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39902. */
  39903. _this.invertNormalMapX = false;
  39904. /**
  39905. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39906. */
  39907. _this.invertNormalMapY = false;
  39908. /**
  39909. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39910. */
  39911. _this.twoSidedLighting = false;
  39912. /**
  39913. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39914. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39915. */
  39916. _this.useAlphaFresnel = 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 stays linear to compute the fresnel)
  39920. */
  39921. _this.useLinearAlphaFresnel = 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.
  39925. */
  39926. _this.environmentBRDFTexture = null;
  39927. /**
  39928. * Force normal to face away from face.
  39929. */
  39930. _this.forceNormalForward = false;
  39931. /**
  39932. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39933. * makes the reflect vector face the model (under horizon).
  39934. */
  39935. _this.useHorizonOcclusion = true;
  39936. /**
  39937. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39938. * too much the area relying on ambient texture to define their ambient occlusion.
  39939. */
  39940. _this.useRadianceOcclusion = true;
  39941. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39942. return _this;
  39943. }
  39944. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39945. /**
  39946. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39947. */
  39948. get: function () {
  39949. return this._PBRMATERIAL_OPAQUE;
  39950. },
  39951. enumerable: true,
  39952. configurable: true
  39953. });
  39954. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39955. /**
  39956. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39957. */
  39958. get: function () {
  39959. return this._PBRMATERIAL_ALPHATEST;
  39960. },
  39961. enumerable: true,
  39962. configurable: true
  39963. });
  39964. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39965. /**
  39966. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39967. */
  39968. get: function () {
  39969. return this._PBRMATERIAL_ALPHABLEND;
  39970. },
  39971. enumerable: true,
  39972. configurable: true
  39973. });
  39974. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39975. /**
  39976. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39977. * They are also discarded below the alpha cutoff threshold to improve performances.
  39978. */
  39979. get: function () {
  39980. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39986. /**
  39987. * Gets the image processing configuration used either in this material.
  39988. */
  39989. get: function () {
  39990. return this._imageProcessingConfiguration;
  39991. },
  39992. /**
  39993. * Sets the Default image processing configuration used either in the this material.
  39994. *
  39995. * If sets to null, the scene one is in use.
  39996. */
  39997. set: function (value) {
  39998. this._attachImageProcessingConfiguration(value);
  39999. // Ensure the effect will be rebuilt.
  40000. this._markAllSubMeshesAsTexturesDirty();
  40001. },
  40002. enumerable: true,
  40003. configurable: true
  40004. });
  40005. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  40006. /**
  40007. * Gets wether the color curves effect is enabled.
  40008. */
  40009. get: function () {
  40010. return this.imageProcessingConfiguration.colorCurvesEnabled;
  40011. },
  40012. /**
  40013. * Sets wether the color curves effect is enabled.
  40014. */
  40015. set: function (value) {
  40016. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  40017. },
  40018. enumerable: true,
  40019. configurable: true
  40020. });
  40021. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  40022. /**
  40023. * Gets wether the color grading effect is enabled.
  40024. */
  40025. get: function () {
  40026. return this.imageProcessingConfiguration.colorGradingEnabled;
  40027. },
  40028. /**
  40029. * Gets wether the color grading effect is enabled.
  40030. */
  40031. set: function (value) {
  40032. this.imageProcessingConfiguration.colorGradingEnabled = value;
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  40038. /**
  40039. * Gets wether tonemapping is enabled or not.
  40040. */
  40041. get: function () {
  40042. return this._imageProcessingConfiguration.toneMappingEnabled;
  40043. },
  40044. /**
  40045. * Sets wether tonemapping is enabled or not
  40046. */
  40047. set: function (value) {
  40048. this._imageProcessingConfiguration.toneMappingEnabled = value;
  40049. },
  40050. enumerable: true,
  40051. configurable: true
  40052. });
  40053. ;
  40054. ;
  40055. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  40056. /**
  40057. * The camera exposure used on this material.
  40058. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40059. * This corresponds to a photographic exposure.
  40060. */
  40061. get: function () {
  40062. return this._imageProcessingConfiguration.exposure;
  40063. },
  40064. /**
  40065. * The camera exposure used on this material.
  40066. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40067. * This corresponds to a photographic exposure.
  40068. */
  40069. set: function (value) {
  40070. this._imageProcessingConfiguration.exposure = value;
  40071. },
  40072. enumerable: true,
  40073. configurable: true
  40074. });
  40075. ;
  40076. ;
  40077. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  40078. /**
  40079. * Gets The camera contrast used on this material.
  40080. */
  40081. get: function () {
  40082. return this._imageProcessingConfiguration.contrast;
  40083. },
  40084. /**
  40085. * Sets The camera contrast used on this material.
  40086. */
  40087. set: function (value) {
  40088. this._imageProcessingConfiguration.contrast = value;
  40089. },
  40090. enumerable: true,
  40091. configurable: true
  40092. });
  40093. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  40094. /**
  40095. * Gets the Color Grading 2D Lookup Texture.
  40096. */
  40097. get: function () {
  40098. return this._imageProcessingConfiguration.colorGradingTexture;
  40099. },
  40100. /**
  40101. * Sets the Color Grading 2D Lookup Texture.
  40102. */
  40103. set: function (value) {
  40104. this._imageProcessingConfiguration.colorGradingTexture = value;
  40105. },
  40106. enumerable: true,
  40107. configurable: true
  40108. });
  40109. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  40110. /**
  40111. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40112. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40113. * 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;
  40114. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40115. */
  40116. get: function () {
  40117. return this._imageProcessingConfiguration.colorCurves;
  40118. },
  40119. /**
  40120. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40121. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40122. * 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;
  40123. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40124. */
  40125. set: function (value) {
  40126. this._imageProcessingConfiguration.colorCurves = value;
  40127. },
  40128. enumerable: true,
  40129. configurable: true
  40130. });
  40131. PBRMaterial.prototype.getClassName = function () {
  40132. return "PBRMaterial";
  40133. };
  40134. PBRMaterial.prototype.getActiveTextures = function () {
  40135. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40136. if (this._albedoTexture) {
  40137. activeTextures.push(this._albedoTexture);
  40138. }
  40139. if (this._ambientTexture) {
  40140. activeTextures.push(this._ambientTexture);
  40141. }
  40142. if (this._opacityTexture) {
  40143. activeTextures.push(this._opacityTexture);
  40144. }
  40145. if (this._reflectionTexture) {
  40146. activeTextures.push(this._reflectionTexture);
  40147. }
  40148. if (this._emissiveTexture) {
  40149. activeTextures.push(this._emissiveTexture);
  40150. }
  40151. if (this._reflectivityTexture) {
  40152. activeTextures.push(this._reflectivityTexture);
  40153. }
  40154. if (this._metallicTexture) {
  40155. activeTextures.push(this._metallicTexture);
  40156. }
  40157. if (this._microSurfaceTexture) {
  40158. activeTextures.push(this._microSurfaceTexture);
  40159. }
  40160. if (this._bumpTexture) {
  40161. activeTextures.push(this._bumpTexture);
  40162. }
  40163. if (this._lightmapTexture) {
  40164. activeTextures.push(this._lightmapTexture);
  40165. }
  40166. if (this._refractionTexture) {
  40167. activeTextures.push(this._refractionTexture);
  40168. }
  40169. return activeTextures;
  40170. };
  40171. PBRMaterial.prototype.hasTexture = function (texture) {
  40172. if (_super.prototype.hasTexture.call(this, texture)) {
  40173. return true;
  40174. }
  40175. if (this._albedoTexture === texture) {
  40176. return true;
  40177. }
  40178. if (this._ambientTexture === texture) {
  40179. return true;
  40180. }
  40181. if (this._opacityTexture === texture) {
  40182. return true;
  40183. }
  40184. if (this._reflectionTexture === texture) {
  40185. return true;
  40186. }
  40187. if (this._reflectivityTexture === texture) {
  40188. return true;
  40189. }
  40190. if (this._metallicTexture === texture) {
  40191. return true;
  40192. }
  40193. if (this._microSurfaceTexture === texture) {
  40194. return true;
  40195. }
  40196. if (this._bumpTexture === texture) {
  40197. return true;
  40198. }
  40199. if (this._lightmapTexture === texture) {
  40200. return true;
  40201. }
  40202. if (this._refractionTexture === texture) {
  40203. return true;
  40204. }
  40205. return false;
  40206. };
  40207. PBRMaterial.prototype.clone = function (name) {
  40208. var _this = this;
  40209. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  40210. clone.id = name;
  40211. clone.name = name;
  40212. return clone;
  40213. };
  40214. PBRMaterial.prototype.serialize = function () {
  40215. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40216. serializationObject.customType = "BABYLON.PBRMaterial";
  40217. return serializationObject;
  40218. };
  40219. // Statics
  40220. PBRMaterial.Parse = function (source, scene, rootUrl) {
  40221. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  40222. };
  40223. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  40224. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  40225. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  40226. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  40227. __decorate([
  40228. BABYLON.serialize(),
  40229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40230. ], PBRMaterial.prototype, "directIntensity", void 0);
  40231. __decorate([
  40232. BABYLON.serialize(),
  40233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40234. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  40235. __decorate([
  40236. BABYLON.serialize(),
  40237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40238. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  40239. __decorate([
  40240. BABYLON.serialize(),
  40241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40242. ], PBRMaterial.prototype, "specularIntensity", void 0);
  40243. __decorate([
  40244. BABYLON.serialize(),
  40245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40246. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  40247. __decorate([
  40248. BABYLON.serializeAsTexture(),
  40249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40250. ], PBRMaterial.prototype, "albedoTexture", void 0);
  40251. __decorate([
  40252. BABYLON.serializeAsTexture(),
  40253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40254. ], PBRMaterial.prototype, "ambientTexture", void 0);
  40255. __decorate([
  40256. BABYLON.serialize(),
  40257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40258. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  40259. __decorate([
  40260. BABYLON.serializeAsTexture(),
  40261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40262. ], PBRMaterial.prototype, "opacityTexture", void 0);
  40263. __decorate([
  40264. BABYLON.serializeAsTexture(),
  40265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40266. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  40267. __decorate([
  40268. BABYLON.serializeAsTexture(),
  40269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40270. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  40271. __decorate([
  40272. BABYLON.serializeAsTexture(),
  40273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40274. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  40275. __decorate([
  40276. BABYLON.serializeAsTexture(),
  40277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40278. ], PBRMaterial.prototype, "metallicTexture", void 0);
  40279. __decorate([
  40280. BABYLON.serialize(),
  40281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40282. ], PBRMaterial.prototype, "metallic", void 0);
  40283. __decorate([
  40284. BABYLON.serialize(),
  40285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40286. ], PBRMaterial.prototype, "roughness", void 0);
  40287. __decorate([
  40288. BABYLON.serializeAsTexture(),
  40289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40290. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  40291. __decorate([
  40292. BABYLON.serializeAsTexture(),
  40293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40294. ], PBRMaterial.prototype, "bumpTexture", void 0);
  40295. __decorate([
  40296. BABYLON.serializeAsTexture(),
  40297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40298. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  40299. __decorate([
  40300. BABYLON.serializeAsTexture(),
  40301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40302. ], PBRMaterial.prototype, "refractionTexture", void 0);
  40303. __decorate([
  40304. BABYLON.serializeAsColor3("ambient"),
  40305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40306. ], PBRMaterial.prototype, "ambientColor", void 0);
  40307. __decorate([
  40308. BABYLON.serializeAsColor3("albedo"),
  40309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40310. ], PBRMaterial.prototype, "albedoColor", void 0);
  40311. __decorate([
  40312. BABYLON.serializeAsColor3("reflectivity"),
  40313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40314. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  40315. __decorate([
  40316. BABYLON.serializeAsColor3("reflection"),
  40317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40318. ], PBRMaterial.prototype, "reflectionColor", void 0);
  40319. __decorate([
  40320. BABYLON.serializeAsColor3("emissive"),
  40321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40322. ], PBRMaterial.prototype, "emissiveColor", void 0);
  40323. __decorate([
  40324. BABYLON.serialize(),
  40325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40326. ], PBRMaterial.prototype, "microSurface", void 0);
  40327. __decorate([
  40328. BABYLON.serialize(),
  40329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40330. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  40331. __decorate([
  40332. BABYLON.serialize(),
  40333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40334. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  40335. __decorate([
  40336. BABYLON.serialize(),
  40337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40338. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  40339. __decorate([
  40340. BABYLON.serialize(),
  40341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40342. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40343. __decorate([
  40344. BABYLON.serialize(),
  40345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40346. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40347. __decorate([
  40348. BABYLON.serialize(),
  40349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40350. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  40351. __decorate([
  40352. BABYLON.serialize(),
  40353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40354. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  40355. __decorate([
  40356. BABYLON.serialize(),
  40357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40358. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40359. __decorate([
  40360. BABYLON.serialize(),
  40361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40362. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40363. __decorate([
  40364. BABYLON.serialize(),
  40365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40366. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40367. __decorate([
  40368. BABYLON.serialize(),
  40369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40370. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40371. __decorate([
  40372. BABYLON.serialize(),
  40373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40374. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40375. __decorate([
  40376. BABYLON.serialize(),
  40377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40378. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40379. __decorate([
  40380. BABYLON.serialize(),
  40381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40382. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40383. __decorate([
  40384. BABYLON.serialize(),
  40385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40386. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40387. __decorate([
  40388. BABYLON.serialize(),
  40389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40390. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40391. __decorate([
  40392. BABYLON.serialize(),
  40393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40394. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40395. __decorate([
  40396. BABYLON.serialize(),
  40397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40398. ], PBRMaterial.prototype, "useParallax", void 0);
  40399. __decorate([
  40400. BABYLON.serialize(),
  40401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40402. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40403. __decorate([
  40404. BABYLON.serialize(),
  40405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40406. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40407. __decorate([
  40408. BABYLON.serialize(),
  40409. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40410. ], PBRMaterial.prototype, "disableLighting", void 0);
  40411. __decorate([
  40412. BABYLON.serialize(),
  40413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40414. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40415. __decorate([
  40416. BABYLON.serialize(),
  40417. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40418. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40419. __decorate([
  40420. BABYLON.serialize(),
  40421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40422. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40423. __decorate([
  40424. BABYLON.serialize(),
  40425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40426. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40427. __decorate([
  40428. BABYLON.serialize(),
  40429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40430. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40431. __decorate([
  40432. BABYLON.serialize(),
  40433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40434. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40435. __decorate([
  40436. BABYLON.serialize(),
  40437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40438. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40439. __decorate([
  40440. BABYLON.serializeAsTexture(),
  40441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40442. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40443. __decorate([
  40444. BABYLON.serialize(),
  40445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40446. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40447. __decorate([
  40448. BABYLON.serialize(),
  40449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40450. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40451. __decorate([
  40452. BABYLON.serialize(),
  40453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40454. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40455. return PBRMaterial;
  40456. }(BABYLON.PBRBaseMaterial));
  40457. BABYLON.PBRMaterial = PBRMaterial;
  40458. })(BABYLON || (BABYLON = {}));
  40459. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40460. var BABYLON;
  40461. (function (BABYLON) {
  40462. /**
  40463. * The PBR material of BJS following the metal roughness convention.
  40464. *
  40465. * This fits to the PBR convention in the GLTF definition:
  40466. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40467. */
  40468. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40469. __extends(PBRMetallicRoughnessMaterial, _super);
  40470. /**
  40471. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40472. *
  40473. * @param name The material name
  40474. * @param scene The scene the material will be use in.
  40475. */
  40476. function PBRMetallicRoughnessMaterial(name, scene) {
  40477. var _this = _super.call(this, name, scene) || this;
  40478. _this._useRoughnessFromMetallicTextureAlpha = false;
  40479. _this._useRoughnessFromMetallicTextureGreen = true;
  40480. _this._useMetallnessFromMetallicTextureBlue = true;
  40481. _this._forceMetallicWorkflow = true;
  40482. return _this;
  40483. }
  40484. /**
  40485. * Return the currrent class name of the material.
  40486. */
  40487. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40488. return "PBRMetallicRoughnessMaterial";
  40489. };
  40490. /**
  40491. * Return the active textures of the material.
  40492. */
  40493. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40494. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40495. if (this.baseTexture) {
  40496. activeTextures.push(this.baseTexture);
  40497. }
  40498. if (this.metallicRoughnessTexture) {
  40499. activeTextures.push(this.metallicRoughnessTexture);
  40500. }
  40501. return activeTextures;
  40502. };
  40503. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40504. if (_super.prototype.hasTexture.call(this, texture)) {
  40505. return true;
  40506. }
  40507. if (this.baseTexture === texture) {
  40508. return true;
  40509. }
  40510. if (this.metallicRoughnessTexture === texture) {
  40511. return true;
  40512. }
  40513. return false;
  40514. };
  40515. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40516. var _this = this;
  40517. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40518. clone.id = name;
  40519. clone.name = name;
  40520. return clone;
  40521. };
  40522. /**
  40523. * Serialize the material to a parsable JSON object.
  40524. */
  40525. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40526. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40527. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40528. return serializationObject;
  40529. };
  40530. /**
  40531. * Parses a JSON object correponding to the serialize function.
  40532. */
  40533. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40534. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40535. };
  40536. __decorate([
  40537. BABYLON.serializeAsColor3(),
  40538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40539. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40540. __decorate([
  40541. BABYLON.serializeAsTexture(),
  40542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40543. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40544. __decorate([
  40545. BABYLON.serialize(),
  40546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40547. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40548. __decorate([
  40549. BABYLON.serialize(),
  40550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40551. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40552. __decorate([
  40553. BABYLON.serializeAsTexture(),
  40554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40555. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40556. return PBRMetallicRoughnessMaterial;
  40557. }(BABYLON.PBRBaseSimpleMaterial));
  40558. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40559. })(BABYLON || (BABYLON = {}));
  40560. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40561. var BABYLON;
  40562. (function (BABYLON) {
  40563. /**
  40564. * The PBR material of BJS following the specular glossiness convention.
  40565. *
  40566. * This fits to the PBR convention in the GLTF definition:
  40567. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40568. */
  40569. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40570. __extends(PBRSpecularGlossinessMaterial, _super);
  40571. /**
  40572. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40573. *
  40574. * @param name The material name
  40575. * @param scene The scene the material will be use in.
  40576. */
  40577. function PBRSpecularGlossinessMaterial(name, scene) {
  40578. var _this = _super.call(this, name, scene) || this;
  40579. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40580. return _this;
  40581. }
  40582. /**
  40583. * Return the currrent class name of the material.
  40584. */
  40585. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40586. return "PBRSpecularGlossinessMaterial";
  40587. };
  40588. /**
  40589. * Return the active textures of the material.
  40590. */
  40591. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40592. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40593. if (this.diffuseTexture) {
  40594. activeTextures.push(this.diffuseTexture);
  40595. }
  40596. if (this.specularGlossinessTexture) {
  40597. activeTextures.push(this.specularGlossinessTexture);
  40598. }
  40599. return activeTextures;
  40600. };
  40601. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40602. if (_super.prototype.hasTexture.call(this, texture)) {
  40603. return true;
  40604. }
  40605. if (this.diffuseTexture === texture) {
  40606. return true;
  40607. }
  40608. if (this.specularGlossinessTexture === texture) {
  40609. return true;
  40610. }
  40611. return false;
  40612. };
  40613. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40614. var _this = this;
  40615. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40616. clone.id = name;
  40617. clone.name = name;
  40618. return clone;
  40619. };
  40620. /**
  40621. * Serialize the material to a parsable JSON object.
  40622. */
  40623. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40624. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40625. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40626. return serializationObject;
  40627. };
  40628. /**
  40629. * Parses a JSON object correponding to the serialize function.
  40630. */
  40631. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40632. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40633. };
  40634. __decorate([
  40635. BABYLON.serializeAsColor3("diffuse"),
  40636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40637. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40638. __decorate([
  40639. BABYLON.serializeAsTexture(),
  40640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40641. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40642. __decorate([
  40643. BABYLON.serializeAsColor3("specular"),
  40644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40645. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40646. __decorate([
  40647. BABYLON.serialize(),
  40648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40649. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40650. __decorate([
  40651. BABYLON.serializeAsTexture(),
  40652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40653. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40654. return PBRSpecularGlossinessMaterial;
  40655. }(BABYLON.PBRBaseSimpleMaterial));
  40656. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40657. })(BABYLON || (BABYLON = {}));
  40658. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40659. var BABYLON;
  40660. (function (BABYLON) {
  40661. BABYLON.CameraInputTypes = {};
  40662. var CameraInputsManager = /** @class */ (function () {
  40663. function CameraInputsManager(camera) {
  40664. this.attached = {};
  40665. this.camera = camera;
  40666. this.checkInputs = function () { };
  40667. }
  40668. /**
  40669. * Add an input method to a camera.
  40670. * builtin inputs example: camera.inputs.addGamepad();
  40671. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40672. * @param input camera input method
  40673. */
  40674. CameraInputsManager.prototype.add = function (input) {
  40675. var type = input.getSimpleName();
  40676. if (this.attached[type]) {
  40677. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40678. return;
  40679. }
  40680. this.attached[type] = input;
  40681. input.camera = this.camera;
  40682. //for checkInputs, we are dynamically creating a function
  40683. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40684. if (input.checkInputs) {
  40685. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40686. }
  40687. if (this.attachedElement) {
  40688. input.attachControl(this.attachedElement);
  40689. }
  40690. };
  40691. /**
  40692. * Remove a specific input method from a camera
  40693. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40694. * @param inputToRemove camera input method
  40695. */
  40696. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40697. for (var cam in this.attached) {
  40698. var input = this.attached[cam];
  40699. if (input === inputToRemove) {
  40700. input.detachControl(this.attachedElement);
  40701. input.camera = null;
  40702. delete this.attached[cam];
  40703. this.rebuildInputCheck();
  40704. }
  40705. }
  40706. };
  40707. CameraInputsManager.prototype.removeByType = function (inputType) {
  40708. for (var cam in this.attached) {
  40709. var input = this.attached[cam];
  40710. if (input.getClassName() === inputType) {
  40711. input.detachControl(this.attachedElement);
  40712. input.camera = null;
  40713. delete this.attached[cam];
  40714. this.rebuildInputCheck();
  40715. }
  40716. }
  40717. };
  40718. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40719. var current = this.checkInputs;
  40720. return function () {
  40721. current();
  40722. fn();
  40723. };
  40724. };
  40725. CameraInputsManager.prototype.attachInput = function (input) {
  40726. if (this.attachedElement) {
  40727. input.attachControl(this.attachedElement, this.noPreventDefault);
  40728. }
  40729. };
  40730. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40731. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40732. if (this.attachedElement) {
  40733. return;
  40734. }
  40735. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40736. this.attachedElement = element;
  40737. this.noPreventDefault = noPreventDefault;
  40738. for (var cam in this.attached) {
  40739. this.attached[cam].attachControl(element, noPreventDefault);
  40740. }
  40741. };
  40742. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40743. if (disconnect === void 0) { disconnect = false; }
  40744. if (this.attachedElement !== element) {
  40745. return;
  40746. }
  40747. for (var cam in this.attached) {
  40748. this.attached[cam].detachControl(element);
  40749. if (disconnect) {
  40750. this.attached[cam].camera = null;
  40751. }
  40752. }
  40753. this.attachedElement = null;
  40754. };
  40755. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40756. this.checkInputs = function () { };
  40757. for (var cam in this.attached) {
  40758. var input = this.attached[cam];
  40759. if (input.checkInputs) {
  40760. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40761. }
  40762. }
  40763. };
  40764. /**
  40765. * Remove all attached input methods from a camera
  40766. */
  40767. CameraInputsManager.prototype.clear = function () {
  40768. if (this.attachedElement) {
  40769. this.detachElement(this.attachedElement, true);
  40770. }
  40771. this.attached = {};
  40772. this.attachedElement = null;
  40773. this.checkInputs = function () { };
  40774. };
  40775. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40776. var inputs = {};
  40777. for (var cam in this.attached) {
  40778. var input = this.attached[cam];
  40779. var res = BABYLON.SerializationHelper.Serialize(input);
  40780. inputs[input.getClassName()] = res;
  40781. }
  40782. serializedCamera.inputsmgr = inputs;
  40783. };
  40784. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40785. var parsedInputs = parsedCamera.inputsmgr;
  40786. if (parsedInputs) {
  40787. this.clear();
  40788. for (var n in parsedInputs) {
  40789. var construct = BABYLON.CameraInputTypes[n];
  40790. if (construct) {
  40791. var parsedinput = parsedInputs[n];
  40792. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40793. this.add(input);
  40794. }
  40795. }
  40796. }
  40797. else {
  40798. //2016-03-08 this part is for managing backward compatibility
  40799. for (var n in this.attached) {
  40800. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40801. if (construct) {
  40802. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40803. this.remove(this.attached[n]);
  40804. this.add(input);
  40805. }
  40806. }
  40807. }
  40808. };
  40809. return CameraInputsManager;
  40810. }());
  40811. BABYLON.CameraInputsManager = CameraInputsManager;
  40812. })(BABYLON || (BABYLON = {}));
  40813. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40814. var BABYLON;
  40815. (function (BABYLON) {
  40816. var TargetCamera = /** @class */ (function (_super) {
  40817. __extends(TargetCamera, _super);
  40818. function TargetCamera(name, position, scene) {
  40819. var _this = _super.call(this, name, position, scene) || this;
  40820. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40821. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40822. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40823. _this.speed = 2.0;
  40824. _this.noRotationConstraint = false;
  40825. _this.lockedTarget = null;
  40826. _this._currentTarget = BABYLON.Vector3.Zero();
  40827. _this._viewMatrix = BABYLON.Matrix.Zero();
  40828. _this._camMatrix = BABYLON.Matrix.Zero();
  40829. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40830. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40831. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40832. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40833. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40834. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40835. _this._tempMatrix = BABYLON.Matrix.Zero();
  40836. return _this;
  40837. }
  40838. TargetCamera.prototype.getFrontPosition = function (distance) {
  40839. this.getWorldMatrix();
  40840. var direction = this.getTarget().subtract(this.position);
  40841. direction.normalize();
  40842. direction.scaleInPlace(distance);
  40843. return this.globalPosition.add(direction);
  40844. };
  40845. TargetCamera.prototype._getLockedTargetPosition = function () {
  40846. if (!this.lockedTarget) {
  40847. return null;
  40848. }
  40849. if (this.lockedTarget.absolutePosition) {
  40850. this.lockedTarget.computeWorldMatrix();
  40851. }
  40852. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40853. };
  40854. TargetCamera.prototype.storeState = function () {
  40855. this._storedPosition = this.position.clone();
  40856. this._storedRotation = this.rotation.clone();
  40857. if (this.rotationQuaternion) {
  40858. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40859. }
  40860. return _super.prototype.storeState.call(this);
  40861. };
  40862. /**
  40863. * Restored camera state. You must call storeState() first
  40864. */
  40865. TargetCamera.prototype._restoreStateValues = function () {
  40866. if (!_super.prototype._restoreStateValues.call(this)) {
  40867. return false;
  40868. }
  40869. this.position = this._storedPosition.clone();
  40870. this.rotation = this._storedRotation.clone();
  40871. if (this.rotationQuaternion) {
  40872. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40873. }
  40874. this.cameraDirection.copyFromFloats(0, 0, 0);
  40875. this.cameraRotation.copyFromFloats(0, 0);
  40876. return true;
  40877. };
  40878. // Cache
  40879. TargetCamera.prototype._initCache = function () {
  40880. _super.prototype._initCache.call(this);
  40881. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40882. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40883. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40884. };
  40885. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40886. if (!ignoreParentClass) {
  40887. _super.prototype._updateCache.call(this);
  40888. }
  40889. var lockedTargetPosition = this._getLockedTargetPosition();
  40890. if (!lockedTargetPosition) {
  40891. this._cache.lockedTarget = null;
  40892. }
  40893. else {
  40894. if (!this._cache.lockedTarget) {
  40895. this._cache.lockedTarget = lockedTargetPosition.clone();
  40896. }
  40897. else {
  40898. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40899. }
  40900. }
  40901. this._cache.rotation.copyFrom(this.rotation);
  40902. if (this.rotationQuaternion)
  40903. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40904. };
  40905. // Synchronized
  40906. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40907. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40908. return false;
  40909. }
  40910. var lockedTargetPosition = this._getLockedTargetPosition();
  40911. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40912. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40913. };
  40914. // Methods
  40915. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40916. var engine = this.getEngine();
  40917. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40918. };
  40919. // Target
  40920. TargetCamera.prototype.setTarget = function (target) {
  40921. this.upVector.normalize();
  40922. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40923. this._camMatrix.invert();
  40924. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40925. var vDir = target.subtract(this.position);
  40926. if (vDir.x >= 0.0) {
  40927. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40928. }
  40929. else {
  40930. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40931. }
  40932. this.rotation.z = 0;
  40933. if (isNaN(this.rotation.x)) {
  40934. this.rotation.x = 0;
  40935. }
  40936. if (isNaN(this.rotation.y)) {
  40937. this.rotation.y = 0;
  40938. }
  40939. if (isNaN(this.rotation.z)) {
  40940. this.rotation.z = 0;
  40941. }
  40942. if (this.rotationQuaternion) {
  40943. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40944. }
  40945. };
  40946. /**
  40947. * Return the current target position of the camera. This value is expressed in local space.
  40948. */
  40949. TargetCamera.prototype.getTarget = function () {
  40950. return this._currentTarget;
  40951. };
  40952. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40953. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40954. };
  40955. TargetCamera.prototype._updatePosition = function () {
  40956. if (this.parent) {
  40957. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40958. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40959. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40960. return;
  40961. }
  40962. this.position.addInPlace(this.cameraDirection);
  40963. };
  40964. TargetCamera.prototype._checkInputs = function () {
  40965. var needToMove = this._decideIfNeedsToMove();
  40966. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40967. // Move
  40968. if (needToMove) {
  40969. this._updatePosition();
  40970. }
  40971. // Rotate
  40972. if (needToRotate) {
  40973. this.rotation.x += this.cameraRotation.x;
  40974. this.rotation.y += this.cameraRotation.y;
  40975. //rotate, if quaternion is set and rotation was used
  40976. if (this.rotationQuaternion) {
  40977. var len = this.rotation.lengthSquared();
  40978. if (len) {
  40979. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40980. }
  40981. }
  40982. if (!this.noRotationConstraint) {
  40983. var limit = (Math.PI / 2) * 0.95;
  40984. if (this.rotation.x > limit)
  40985. this.rotation.x = limit;
  40986. if (this.rotation.x < -limit)
  40987. this.rotation.x = -limit;
  40988. }
  40989. }
  40990. // Inertia
  40991. if (needToMove) {
  40992. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40993. this.cameraDirection.x = 0;
  40994. }
  40995. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40996. this.cameraDirection.y = 0;
  40997. }
  40998. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40999. this.cameraDirection.z = 0;
  41000. }
  41001. this.cameraDirection.scaleInPlace(this.inertia);
  41002. }
  41003. if (needToRotate) {
  41004. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  41005. this.cameraRotation.x = 0;
  41006. }
  41007. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  41008. this.cameraRotation.y = 0;
  41009. }
  41010. this.cameraRotation.scaleInPlace(this.inertia);
  41011. }
  41012. _super.prototype._checkInputs.call(this);
  41013. };
  41014. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  41015. if (this.rotationQuaternion) {
  41016. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  41017. }
  41018. else {
  41019. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  41020. }
  41021. //update the up vector!
  41022. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  41023. };
  41024. TargetCamera.prototype._getViewMatrix = function () {
  41025. if (this.lockedTarget) {
  41026. this.setTarget(this._getLockedTargetPosition());
  41027. }
  41028. // Compute
  41029. this._updateCameraRotationMatrix();
  41030. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  41031. // Computing target and final matrix
  41032. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  41033. if (this.getScene().useRightHandedSystem) {
  41034. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  41035. }
  41036. else {
  41037. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  41038. }
  41039. return this._viewMatrix;
  41040. };
  41041. /**
  41042. * @override
  41043. * Override Camera.createRigCamera
  41044. */
  41045. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  41046. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  41047. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  41048. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  41049. if (!this.rotationQuaternion) {
  41050. this.rotationQuaternion = new BABYLON.Quaternion();
  41051. }
  41052. rigCamera._cameraRigParams = {};
  41053. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  41054. }
  41055. return rigCamera;
  41056. }
  41057. return null;
  41058. };
  41059. /**
  41060. * @override
  41061. * Override Camera._updateRigCameras
  41062. */
  41063. TargetCamera.prototype._updateRigCameras = function () {
  41064. var camLeft = this._rigCameras[0];
  41065. var camRight = this._rigCameras[1];
  41066. switch (this.cameraRigMode) {
  41067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41068. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41069. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41070. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41071. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  41072. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  41073. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  41074. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  41075. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  41076. camLeft.setTarget(this.getTarget());
  41077. camRight.setTarget(this.getTarget());
  41078. break;
  41079. case BABYLON.Camera.RIG_MODE_VR:
  41080. if (camLeft.rotationQuaternion) {
  41081. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  41082. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  41083. }
  41084. else {
  41085. camLeft.rotation.copyFrom(this.rotation);
  41086. camRight.rotation.copyFrom(this.rotation);
  41087. }
  41088. camLeft.position.copyFrom(this.position);
  41089. camRight.position.copyFrom(this.position);
  41090. break;
  41091. }
  41092. _super.prototype._updateRigCameras.call(this);
  41093. };
  41094. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  41095. if (!this._rigCamTransformMatrix) {
  41096. this._rigCamTransformMatrix = new BABYLON.Matrix();
  41097. }
  41098. var target = this.getTarget();
  41099. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  41100. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  41101. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  41102. };
  41103. TargetCamera.prototype.getClassName = function () {
  41104. return "TargetCamera";
  41105. };
  41106. __decorate([
  41107. BABYLON.serializeAsVector3()
  41108. ], TargetCamera.prototype, "rotation", void 0);
  41109. __decorate([
  41110. BABYLON.serialize()
  41111. ], TargetCamera.prototype, "speed", void 0);
  41112. __decorate([
  41113. BABYLON.serializeAsMeshReference("lockedTargetId")
  41114. ], TargetCamera.prototype, "lockedTarget", void 0);
  41115. return TargetCamera;
  41116. }(BABYLON.Camera));
  41117. BABYLON.TargetCamera = TargetCamera;
  41118. })(BABYLON || (BABYLON = {}));
  41119. //# sourceMappingURL=babylon.targetCamera.js.map
  41120. var BABYLON;
  41121. (function (BABYLON) {
  41122. var FreeCameraMouseInput = /** @class */ (function () {
  41123. function FreeCameraMouseInput(touchEnabled) {
  41124. if (touchEnabled === void 0) { touchEnabled = true; }
  41125. this.touchEnabled = touchEnabled;
  41126. this.buttons = [0, 1, 2];
  41127. this.angularSensibility = 2000.0;
  41128. this.previousPosition = null;
  41129. }
  41130. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  41131. var _this = this;
  41132. var engine = this.camera.getEngine();
  41133. if (!this._pointerInput) {
  41134. this._pointerInput = function (p, s) {
  41135. var evt = p.event;
  41136. if (engine.isInVRExclusivePointerMode) {
  41137. return;
  41138. }
  41139. if (!_this.touchEnabled && evt.pointerType === "touch") {
  41140. return;
  41141. }
  41142. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41143. return;
  41144. }
  41145. var srcElement = (evt.srcElement || evt.target);
  41146. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41147. try {
  41148. srcElement.setPointerCapture(evt.pointerId);
  41149. }
  41150. catch (e) {
  41151. //Nothing to do with the error. Execution will continue.
  41152. }
  41153. _this.previousPosition = {
  41154. x: evt.clientX,
  41155. y: evt.clientY
  41156. };
  41157. if (!noPreventDefault) {
  41158. evt.preventDefault();
  41159. element.focus();
  41160. }
  41161. }
  41162. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41163. try {
  41164. srcElement.releasePointerCapture(evt.pointerId);
  41165. }
  41166. catch (e) {
  41167. //Nothing to do with the error.
  41168. }
  41169. _this.previousPosition = null;
  41170. if (!noPreventDefault) {
  41171. evt.preventDefault();
  41172. }
  41173. }
  41174. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41175. if (!_this.previousPosition || engine.isPointerLock) {
  41176. return;
  41177. }
  41178. var offsetX = evt.clientX - _this.previousPosition.x;
  41179. var offsetY = evt.clientY - _this.previousPosition.y;
  41180. if (_this.camera.getScene().useRightHandedSystem) {
  41181. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41182. }
  41183. else {
  41184. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41185. }
  41186. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41187. _this.previousPosition = {
  41188. x: evt.clientX,
  41189. y: evt.clientY
  41190. };
  41191. if (!noPreventDefault) {
  41192. evt.preventDefault();
  41193. }
  41194. }
  41195. };
  41196. }
  41197. this._onMouseMove = function (evt) {
  41198. if (!engine.isPointerLock) {
  41199. return;
  41200. }
  41201. if (engine.isInVRExclusivePointerMode) {
  41202. return;
  41203. }
  41204. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41205. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41206. if (_this.camera.getScene().useRightHandedSystem) {
  41207. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41208. }
  41209. else {
  41210. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41211. }
  41212. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41213. _this.previousPosition = null;
  41214. if (!noPreventDefault) {
  41215. evt.preventDefault();
  41216. }
  41217. };
  41218. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  41219. element.addEventListener("mousemove", this._onMouseMove, false);
  41220. };
  41221. FreeCameraMouseInput.prototype.detachControl = function (element) {
  41222. if (this._observer && element) {
  41223. this.camera.getScene().onPointerObservable.remove(this._observer);
  41224. if (this._onMouseMove) {
  41225. element.removeEventListener("mousemove", this._onMouseMove);
  41226. }
  41227. this._observer = null;
  41228. this._onMouseMove = null;
  41229. this.previousPosition = null;
  41230. }
  41231. };
  41232. FreeCameraMouseInput.prototype.getClassName = function () {
  41233. return "FreeCameraMouseInput";
  41234. };
  41235. FreeCameraMouseInput.prototype.getSimpleName = function () {
  41236. return "mouse";
  41237. };
  41238. __decorate([
  41239. BABYLON.serialize()
  41240. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  41241. __decorate([
  41242. BABYLON.serialize()
  41243. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  41244. return FreeCameraMouseInput;
  41245. }());
  41246. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  41247. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  41248. })(BABYLON || (BABYLON = {}));
  41249. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  41250. var BABYLON;
  41251. (function (BABYLON) {
  41252. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  41253. function FreeCameraKeyboardMoveInput() {
  41254. this._keys = new Array();
  41255. this.keysUp = [38];
  41256. this.keysDown = [40];
  41257. this.keysLeft = [37];
  41258. this.keysRight = [39];
  41259. }
  41260. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41261. var _this = this;
  41262. if (this._onCanvasBlurObserver) {
  41263. return;
  41264. }
  41265. this._scene = this.camera.getScene();
  41266. this._engine = this._scene.getEngine();
  41267. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41268. _this._keys = [];
  41269. });
  41270. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41271. var evt = info.event;
  41272. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41273. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41274. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41275. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41276. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41277. var index = _this._keys.indexOf(evt.keyCode);
  41278. if (index === -1) {
  41279. _this._keys.push(evt.keyCode);
  41280. }
  41281. if (!noPreventDefault) {
  41282. evt.preventDefault();
  41283. }
  41284. }
  41285. }
  41286. else {
  41287. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41288. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41289. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41290. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41291. var index = _this._keys.indexOf(evt.keyCode);
  41292. if (index >= 0) {
  41293. _this._keys.splice(index, 1);
  41294. }
  41295. if (!noPreventDefault) {
  41296. evt.preventDefault();
  41297. }
  41298. }
  41299. }
  41300. });
  41301. };
  41302. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41303. if (this._scene) {
  41304. if (this._onKeyboardObserver) {
  41305. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41306. }
  41307. if (this._onCanvasBlurObserver) {
  41308. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41309. }
  41310. this._onKeyboardObserver = null;
  41311. this._onCanvasBlurObserver = null;
  41312. }
  41313. this._keys = [];
  41314. };
  41315. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41316. if (this._onKeyboardObserver) {
  41317. var camera = this.camera;
  41318. // Keyboard
  41319. for (var index = 0; index < this._keys.length; index++) {
  41320. var keyCode = this._keys[index];
  41321. var speed = camera._computeLocalCameraSpeed();
  41322. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41323. camera._localDirection.copyFromFloats(-speed, 0, 0);
  41324. }
  41325. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41326. camera._localDirection.copyFromFloats(0, 0, speed);
  41327. }
  41328. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41329. camera._localDirection.copyFromFloats(speed, 0, 0);
  41330. }
  41331. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41332. camera._localDirection.copyFromFloats(0, 0, -speed);
  41333. }
  41334. if (camera.getScene().useRightHandedSystem) {
  41335. camera._localDirection.z *= -1;
  41336. }
  41337. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  41338. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  41339. camera.cameraDirection.addInPlace(camera._transformedDirection);
  41340. }
  41341. }
  41342. };
  41343. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  41344. return "FreeCameraKeyboardMoveInput";
  41345. };
  41346. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  41347. this._keys = [];
  41348. };
  41349. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41350. return "keyboard";
  41351. };
  41352. __decorate([
  41353. BABYLON.serialize()
  41354. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41355. __decorate([
  41356. BABYLON.serialize()
  41357. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41358. __decorate([
  41359. BABYLON.serialize()
  41360. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41361. __decorate([
  41362. BABYLON.serialize()
  41363. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41364. return FreeCameraKeyboardMoveInput;
  41365. }());
  41366. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  41367. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  41368. })(BABYLON || (BABYLON = {}));
  41369. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  41370. var BABYLON;
  41371. (function (BABYLON) {
  41372. var FreeCameraInputsManager = /** @class */ (function (_super) {
  41373. __extends(FreeCameraInputsManager, _super);
  41374. function FreeCameraInputsManager(camera) {
  41375. return _super.call(this, camera) || this;
  41376. }
  41377. FreeCameraInputsManager.prototype.addKeyboard = function () {
  41378. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  41379. return this;
  41380. };
  41381. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  41382. if (touchEnabled === void 0) { touchEnabled = true; }
  41383. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  41384. return this;
  41385. };
  41386. FreeCameraInputsManager.prototype.addGamepad = function () {
  41387. this.add(new BABYLON.FreeCameraGamepadInput());
  41388. return this;
  41389. };
  41390. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  41391. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  41392. return this;
  41393. };
  41394. FreeCameraInputsManager.prototype.addTouch = function () {
  41395. this.add(new BABYLON.FreeCameraTouchInput());
  41396. return this;
  41397. };
  41398. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  41399. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  41400. return this;
  41401. };
  41402. return FreeCameraInputsManager;
  41403. }(BABYLON.CameraInputsManager));
  41404. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  41405. })(BABYLON || (BABYLON = {}));
  41406. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  41407. var BABYLON;
  41408. (function (BABYLON) {
  41409. var FreeCamera = /** @class */ (function (_super) {
  41410. __extends(FreeCamera, _super);
  41411. function FreeCamera(name, position, scene) {
  41412. var _this = _super.call(this, name, position, scene) || this;
  41413. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41414. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41415. _this.checkCollisions = false;
  41416. _this.applyGravity = false;
  41417. _this._needMoveForGravity = false;
  41418. _this._oldPosition = BABYLON.Vector3.Zero();
  41419. _this._diffPosition = BABYLON.Vector3.Zero();
  41420. _this._newPosition = BABYLON.Vector3.Zero();
  41421. // Collisions
  41422. _this._collisionMask = -1;
  41423. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41424. if (collidedMesh === void 0) { collidedMesh = null; }
  41425. //TODO move this to the collision coordinator!
  41426. if (_this.getScene().workerCollisions)
  41427. newPosition.multiplyInPlace(_this._collider._radius);
  41428. var updatePosition = function (newPos) {
  41429. _this._newPosition.copyFrom(newPos);
  41430. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41431. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41432. _this.position.addInPlace(_this._diffPosition);
  41433. if (_this.onCollide && collidedMesh) {
  41434. _this.onCollide(collidedMesh);
  41435. }
  41436. }
  41437. };
  41438. updatePosition(newPosition);
  41439. };
  41440. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41441. _this.inputs.addKeyboard().addMouse();
  41442. return _this;
  41443. }
  41444. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41445. //-- begin properties for backward compatibility for inputs
  41446. /**
  41447. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41448. * Higher values reduce sensitivity.
  41449. */
  41450. get: function () {
  41451. var mouse = this.inputs.attached["mouse"];
  41452. if (mouse)
  41453. return mouse.angularSensibility;
  41454. return 0;
  41455. },
  41456. /**
  41457. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41458. * Higher values reduce sensitivity.
  41459. */
  41460. set: function (value) {
  41461. var mouse = this.inputs.attached["mouse"];
  41462. if (mouse)
  41463. mouse.angularSensibility = value;
  41464. },
  41465. enumerable: true,
  41466. configurable: true
  41467. });
  41468. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41469. get: function () {
  41470. var keyboard = this.inputs.attached["keyboard"];
  41471. if (keyboard)
  41472. return keyboard.keysUp;
  41473. return [];
  41474. },
  41475. set: function (value) {
  41476. var keyboard = this.inputs.attached["keyboard"];
  41477. if (keyboard)
  41478. keyboard.keysUp = value;
  41479. },
  41480. enumerable: true,
  41481. configurable: true
  41482. });
  41483. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41484. get: function () {
  41485. var keyboard = this.inputs.attached["keyboard"];
  41486. if (keyboard)
  41487. return keyboard.keysDown;
  41488. return [];
  41489. },
  41490. set: function (value) {
  41491. var keyboard = this.inputs.attached["keyboard"];
  41492. if (keyboard)
  41493. keyboard.keysDown = value;
  41494. },
  41495. enumerable: true,
  41496. configurable: true
  41497. });
  41498. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41499. get: function () {
  41500. var keyboard = this.inputs.attached["keyboard"];
  41501. if (keyboard)
  41502. return keyboard.keysLeft;
  41503. return [];
  41504. },
  41505. set: function (value) {
  41506. var keyboard = this.inputs.attached["keyboard"];
  41507. if (keyboard)
  41508. keyboard.keysLeft = value;
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41514. get: function () {
  41515. var keyboard = this.inputs.attached["keyboard"];
  41516. if (keyboard)
  41517. return keyboard.keysRight;
  41518. return [];
  41519. },
  41520. set: function (value) {
  41521. var keyboard = this.inputs.attached["keyboard"];
  41522. if (keyboard)
  41523. keyboard.keysRight = value;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. // Controls
  41529. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41530. this.inputs.attachElement(element, noPreventDefault);
  41531. };
  41532. FreeCamera.prototype.detachControl = function (element) {
  41533. this.inputs.detachElement(element);
  41534. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41535. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41536. };
  41537. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41538. get: function () {
  41539. return this._collisionMask;
  41540. },
  41541. set: function (mask) {
  41542. this._collisionMask = !isNaN(mask) ? mask : -1;
  41543. },
  41544. enumerable: true,
  41545. configurable: true
  41546. });
  41547. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41548. var globalPosition;
  41549. if (this.parent) {
  41550. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41551. }
  41552. else {
  41553. globalPosition = this.position;
  41554. }
  41555. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41556. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41557. if (!this._collider) {
  41558. this._collider = new BABYLON.Collider();
  41559. }
  41560. this._collider._radius = this.ellipsoid;
  41561. this._collider.collisionMask = this._collisionMask;
  41562. //no need for clone, as long as gravity is not on.
  41563. var actualDisplacement = displacement;
  41564. //add gravity to the direction to prevent the dual-collision checking
  41565. if (this.applyGravity) {
  41566. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41567. actualDisplacement = displacement.add(this.getScene().gravity);
  41568. }
  41569. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41570. };
  41571. FreeCamera.prototype._checkInputs = function () {
  41572. if (!this._localDirection) {
  41573. this._localDirection = BABYLON.Vector3.Zero();
  41574. this._transformedDirection = BABYLON.Vector3.Zero();
  41575. }
  41576. this.inputs.checkInputs();
  41577. _super.prototype._checkInputs.call(this);
  41578. };
  41579. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41580. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41581. };
  41582. FreeCamera.prototype._updatePosition = function () {
  41583. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41584. this._collideWithWorld(this.cameraDirection);
  41585. }
  41586. else {
  41587. _super.prototype._updatePosition.call(this);
  41588. }
  41589. };
  41590. FreeCamera.prototype.dispose = function () {
  41591. this.inputs.clear();
  41592. _super.prototype.dispose.call(this);
  41593. };
  41594. FreeCamera.prototype.getClassName = function () {
  41595. return "FreeCamera";
  41596. };
  41597. __decorate([
  41598. BABYLON.serializeAsVector3()
  41599. ], FreeCamera.prototype, "ellipsoid", void 0);
  41600. __decorate([
  41601. BABYLON.serializeAsVector3()
  41602. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41603. __decorate([
  41604. BABYLON.serialize()
  41605. ], FreeCamera.prototype, "checkCollisions", void 0);
  41606. __decorate([
  41607. BABYLON.serialize()
  41608. ], FreeCamera.prototype, "applyGravity", void 0);
  41609. return FreeCamera;
  41610. }(BABYLON.TargetCamera));
  41611. BABYLON.FreeCamera = FreeCamera;
  41612. })(BABYLON || (BABYLON = {}));
  41613. //# sourceMappingURL=babylon.freeCamera.js.map
  41614. var BABYLON;
  41615. (function (BABYLON) {
  41616. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41617. function ArcRotateCameraKeyboardMoveInput() {
  41618. this._keys = new Array();
  41619. this.keysUp = [38];
  41620. this.keysDown = [40];
  41621. this.keysLeft = [37];
  41622. this.keysRight = [39];
  41623. this.keysReset = [220];
  41624. this.panningSensibility = 50.0;
  41625. this.zoomingSensibility = 25.0;
  41626. this.useAltToZoom = true;
  41627. }
  41628. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41629. var _this = this;
  41630. if (this._onCanvasBlurObserver) {
  41631. return;
  41632. }
  41633. this._scene = this.camera.getScene();
  41634. this._engine = this._scene.getEngine();
  41635. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41636. _this._keys = [];
  41637. });
  41638. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41639. var evt = info.event;
  41640. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41641. _this._ctrlPressed = evt.ctrlKey;
  41642. _this._altPressed = evt.altKey;
  41643. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41644. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41645. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41646. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41647. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41648. var index = _this._keys.indexOf(evt.keyCode);
  41649. if (index === -1) {
  41650. _this._keys.push(evt.keyCode);
  41651. }
  41652. if (evt.preventDefault) {
  41653. if (!noPreventDefault) {
  41654. evt.preventDefault();
  41655. }
  41656. }
  41657. }
  41658. }
  41659. else {
  41660. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41661. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41662. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41663. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41664. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41665. var index = _this._keys.indexOf(evt.keyCode);
  41666. if (index >= 0) {
  41667. _this._keys.splice(index, 1);
  41668. }
  41669. if (evt.preventDefault) {
  41670. if (!noPreventDefault) {
  41671. evt.preventDefault();
  41672. }
  41673. }
  41674. }
  41675. }
  41676. });
  41677. };
  41678. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41679. if (this._scene) {
  41680. if (this._onKeyboardObserver) {
  41681. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41682. }
  41683. if (this._onCanvasBlurObserver) {
  41684. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41685. }
  41686. this._onKeyboardObserver = null;
  41687. this._onCanvasBlurObserver = null;
  41688. }
  41689. this._keys = [];
  41690. };
  41691. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41692. if (this._onKeyboardObserver) {
  41693. var camera = this.camera;
  41694. for (var index = 0; index < this._keys.length; index++) {
  41695. var keyCode = this._keys[index];
  41696. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41697. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41698. camera.inertialPanningX -= 1 / this.panningSensibility;
  41699. }
  41700. else {
  41701. camera.inertialAlphaOffset -= 0.01;
  41702. }
  41703. }
  41704. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41705. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41706. camera.inertialPanningY += 1 / this.panningSensibility;
  41707. }
  41708. else if (this._altPressed && this.useAltToZoom) {
  41709. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41710. }
  41711. else {
  41712. camera.inertialBetaOffset -= 0.01;
  41713. }
  41714. }
  41715. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41716. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41717. camera.inertialPanningX += 1 / this.panningSensibility;
  41718. }
  41719. else {
  41720. camera.inertialAlphaOffset += 0.01;
  41721. }
  41722. }
  41723. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41724. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41725. camera.inertialPanningY -= 1 / this.panningSensibility;
  41726. }
  41727. else if (this._altPressed && this.useAltToZoom) {
  41728. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41729. }
  41730. else {
  41731. camera.inertialBetaOffset += 0.01;
  41732. }
  41733. }
  41734. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41735. camera.restoreState();
  41736. }
  41737. }
  41738. }
  41739. };
  41740. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41741. return "ArcRotateCameraKeyboardMoveInput";
  41742. };
  41743. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41744. return "keyboard";
  41745. };
  41746. __decorate([
  41747. BABYLON.serialize()
  41748. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41749. __decorate([
  41750. BABYLON.serialize()
  41751. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41752. __decorate([
  41753. BABYLON.serialize()
  41754. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41755. __decorate([
  41756. BABYLON.serialize()
  41757. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41758. __decorate([
  41759. BABYLON.serialize()
  41760. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41761. __decorate([
  41762. BABYLON.serialize()
  41763. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41764. __decorate([
  41765. BABYLON.serialize()
  41766. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41767. __decorate([
  41768. BABYLON.serialize()
  41769. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41770. return ArcRotateCameraKeyboardMoveInput;
  41771. }());
  41772. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41773. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41774. })(BABYLON || (BABYLON = {}));
  41775. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41776. var BABYLON;
  41777. (function (BABYLON) {
  41778. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41779. function ArcRotateCameraMouseWheelInput() {
  41780. this.wheelPrecision = 3.0;
  41781. /**
  41782. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41783. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41784. */
  41785. this.wheelDeltaPercentage = 0;
  41786. }
  41787. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41788. var _this = this;
  41789. this._wheel = function (p, s) {
  41790. //sanity check - this should be a PointerWheel event.
  41791. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41792. return;
  41793. var event = p.event;
  41794. var delta = 0;
  41795. if (event.wheelDelta) {
  41796. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41797. }
  41798. else if (event.detail) {
  41799. delta = -event.detail / _this.wheelPrecision;
  41800. }
  41801. if (delta)
  41802. _this.camera.inertialRadiusOffset += delta;
  41803. if (event.preventDefault) {
  41804. if (!noPreventDefault) {
  41805. event.preventDefault();
  41806. }
  41807. }
  41808. };
  41809. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41810. };
  41811. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41812. if (this._observer && element) {
  41813. this.camera.getScene().onPointerObservable.remove(this._observer);
  41814. this._observer = null;
  41815. this._wheel = null;
  41816. }
  41817. };
  41818. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41819. return "ArcRotateCameraMouseWheelInput";
  41820. };
  41821. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41822. return "mousewheel";
  41823. };
  41824. __decorate([
  41825. BABYLON.serialize()
  41826. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41827. __decorate([
  41828. BABYLON.serialize()
  41829. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41830. return ArcRotateCameraMouseWheelInput;
  41831. }());
  41832. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41833. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41834. })(BABYLON || (BABYLON = {}));
  41835. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41836. var BABYLON;
  41837. (function (BABYLON) {
  41838. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41839. function ArcRotateCameraPointersInput() {
  41840. this.buttons = [0, 1, 2];
  41841. this.angularSensibilityX = 1000.0;
  41842. this.angularSensibilityY = 1000.0;
  41843. this.pinchPrecision = 12.0;
  41844. /**
  41845. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41846. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41847. */
  41848. this.pinchDeltaPercentage = 0;
  41849. this.panningSensibility = 1000.0;
  41850. this.multiTouchPanning = true;
  41851. this.multiTouchPanAndZoom = true;
  41852. this._isPanClick = false;
  41853. this.pinchInwards = true;
  41854. }
  41855. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41856. var _this = this;
  41857. var engine = this.camera.getEngine();
  41858. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41859. var pointA = null;
  41860. var pointB = null;
  41861. var previousPinchSquaredDistance = 0;
  41862. var initialDistance = 0;
  41863. var twoFingerActivityCount = 0;
  41864. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41865. this._pointerInput = function (p, s) {
  41866. var evt = p.event;
  41867. var isTouch = p.event.pointerType === "touch";
  41868. if (engine.isInVRExclusivePointerMode) {
  41869. return;
  41870. }
  41871. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41872. return;
  41873. }
  41874. var srcElement = (evt.srcElement || evt.target);
  41875. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41876. try {
  41877. srcElement.setPointerCapture(evt.pointerId);
  41878. }
  41879. catch (e) {
  41880. //Nothing to do with the error. Execution will continue.
  41881. }
  41882. // Manage panning with pan button click
  41883. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41884. // manage pointers
  41885. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41886. if (pointA === null) {
  41887. pointA = cacheSoloPointer;
  41888. }
  41889. else if (pointB === null) {
  41890. pointB = cacheSoloPointer;
  41891. }
  41892. if (!noPreventDefault) {
  41893. evt.preventDefault();
  41894. element.focus();
  41895. }
  41896. }
  41897. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41898. _this.camera.restoreState();
  41899. }
  41900. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41901. try {
  41902. srcElement.releasePointerCapture(evt.pointerId);
  41903. }
  41904. catch (e) {
  41905. //Nothing to do with the error.
  41906. }
  41907. cacheSoloPointer = null;
  41908. previousPinchSquaredDistance = 0;
  41909. previousMultiTouchPanPosition.isPaning = false;
  41910. previousMultiTouchPanPosition.isPinching = false;
  41911. twoFingerActivityCount = 0;
  41912. initialDistance = 0;
  41913. if (!isTouch) {
  41914. pointB = null; // Mouse and pen are mono pointer
  41915. }
  41916. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41917. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41918. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41919. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41920. if (engine.badOS) {
  41921. pointA = pointB = null;
  41922. }
  41923. else {
  41924. //only remove the impacted pointer in case of multitouch allowing on most
  41925. //platforms switching from rotate to zoom and pan seamlessly.
  41926. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41927. pointA = pointB;
  41928. pointB = null;
  41929. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41930. }
  41931. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41932. pointB = null;
  41933. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41934. }
  41935. else {
  41936. pointA = pointB = null;
  41937. }
  41938. }
  41939. if (!noPreventDefault) {
  41940. evt.preventDefault();
  41941. }
  41942. }
  41943. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41944. if (!noPreventDefault) {
  41945. evt.preventDefault();
  41946. }
  41947. // One button down
  41948. if (pointA && pointB === null && cacheSoloPointer) {
  41949. if (_this.panningSensibility !== 0 &&
  41950. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41951. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41952. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41953. }
  41954. else {
  41955. var offsetX = evt.clientX - cacheSoloPointer.x;
  41956. var offsetY = evt.clientY - cacheSoloPointer.y;
  41957. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41958. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41959. }
  41960. cacheSoloPointer.x = evt.clientX;
  41961. cacheSoloPointer.y = evt.clientY;
  41962. }
  41963. else if (pointA && pointB) {
  41964. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41965. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41966. ed.x = evt.clientX;
  41967. ed.y = evt.clientY;
  41968. var direction = _this.pinchInwards ? 1 : -1;
  41969. var distX = pointA.x - pointB.x;
  41970. var distY = pointA.y - pointB.y;
  41971. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41972. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41973. if (previousPinchSquaredDistance === 0) {
  41974. initialDistance = pinchDistance;
  41975. previousPinchSquaredDistance = pinchSquaredDistance;
  41976. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41977. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41978. return;
  41979. }
  41980. if (_this.multiTouchPanAndZoom) {
  41981. if (_this.pinchDeltaPercentage) {
  41982. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41983. }
  41984. else {
  41985. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41986. (_this.pinchPrecision *
  41987. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41988. direction);
  41989. }
  41990. if (_this.panningSensibility !== 0) {
  41991. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41992. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41993. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41994. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41995. previousMultiTouchPanPosition.x = pointersCenterX;
  41996. previousMultiTouchPanPosition.y = pointersCenterY;
  41997. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41998. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41999. }
  42000. }
  42001. else {
  42002. twoFingerActivityCount++;
  42003. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  42004. if (_this.pinchDeltaPercentage) {
  42005. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  42006. }
  42007. else {
  42008. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  42009. (_this.pinchPrecision *
  42010. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  42011. direction);
  42012. }
  42013. previousMultiTouchPanPosition.isPaning = false;
  42014. previousMultiTouchPanPosition.isPinching = true;
  42015. }
  42016. else {
  42017. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  42018. if (!previousMultiTouchPanPosition.isPaning) {
  42019. previousMultiTouchPanPosition.isPaning = true;
  42020. previousMultiTouchPanPosition.isPinching = false;
  42021. previousMultiTouchPanPosition.x = ed.x;
  42022. previousMultiTouchPanPosition.y = ed.y;
  42023. return;
  42024. }
  42025. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  42026. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  42027. }
  42028. }
  42029. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  42030. previousMultiTouchPanPosition.x = ed.x;
  42031. previousMultiTouchPanPosition.y = ed.y;
  42032. }
  42033. }
  42034. previousPinchSquaredDistance = pinchSquaredDistance;
  42035. }
  42036. }
  42037. };
  42038. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  42039. this._onContextMenu = function (evt) {
  42040. evt.preventDefault();
  42041. };
  42042. if (!this.camera._useCtrlForPanning) {
  42043. element.addEventListener("contextmenu", this._onContextMenu, false);
  42044. }
  42045. this._onLostFocus = function () {
  42046. //this._keys = [];
  42047. pointA = pointB = null;
  42048. previousPinchSquaredDistance = 0;
  42049. previousMultiTouchPanPosition.isPaning = false;
  42050. previousMultiTouchPanPosition.isPinching = false;
  42051. twoFingerActivityCount = 0;
  42052. cacheSoloPointer = null;
  42053. initialDistance = 0;
  42054. };
  42055. this._onMouseMove = function (evt) {
  42056. if (!engine.isPointerLock) {
  42057. return;
  42058. }
  42059. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42060. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42061. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  42062. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  42063. if (!noPreventDefault) {
  42064. evt.preventDefault();
  42065. }
  42066. };
  42067. this._onGestureStart = function (e) {
  42068. if (window.MSGesture === undefined) {
  42069. return;
  42070. }
  42071. if (!_this._MSGestureHandler) {
  42072. _this._MSGestureHandler = new MSGesture();
  42073. _this._MSGestureHandler.target = element;
  42074. }
  42075. _this._MSGestureHandler.addPointer(e.pointerId);
  42076. };
  42077. this._onGesture = function (e) {
  42078. _this.camera.radius *= e.scale;
  42079. if (e.preventDefault) {
  42080. if (!noPreventDefault) {
  42081. e.stopPropagation();
  42082. e.preventDefault();
  42083. }
  42084. }
  42085. };
  42086. element.addEventListener("mousemove", this._onMouseMove, false);
  42087. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  42088. element.addEventListener("MSGestureChange", this._onGesture, false);
  42089. BABYLON.Tools.RegisterTopRootEvents([
  42090. { name: "blur", handler: this._onLostFocus }
  42091. ]);
  42092. };
  42093. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  42094. if (this._onLostFocus) {
  42095. BABYLON.Tools.UnregisterTopRootEvents([
  42096. { name: "blur", handler: this._onLostFocus }
  42097. ]);
  42098. }
  42099. if (element && this._observer) {
  42100. this.camera.getScene().onPointerObservable.remove(this._observer);
  42101. this._observer = null;
  42102. if (this._onContextMenu) {
  42103. element.removeEventListener("contextmenu", this._onContextMenu);
  42104. }
  42105. if (this._onMouseMove) {
  42106. element.removeEventListener("mousemove", this._onMouseMove);
  42107. }
  42108. if (this._onGestureStart) {
  42109. element.removeEventListener("MSPointerDown", this._onGestureStart);
  42110. }
  42111. if (this._onGesture) {
  42112. element.removeEventListener("MSGestureChange", this._onGesture);
  42113. }
  42114. this._isPanClick = false;
  42115. this.pinchInwards = true;
  42116. this._onMouseMove = null;
  42117. this._onGestureStart = null;
  42118. this._onGesture = null;
  42119. this._MSGestureHandler = null;
  42120. this._onLostFocus = null;
  42121. this._onContextMenu = null;
  42122. }
  42123. };
  42124. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  42125. return "ArcRotateCameraPointersInput";
  42126. };
  42127. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  42128. return "pointers";
  42129. };
  42130. __decorate([
  42131. BABYLON.serialize()
  42132. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  42133. __decorate([
  42134. BABYLON.serialize()
  42135. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  42136. __decorate([
  42137. BABYLON.serialize()
  42138. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  42139. __decorate([
  42140. BABYLON.serialize()
  42141. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  42142. __decorate([
  42143. BABYLON.serialize()
  42144. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  42145. __decorate([
  42146. BABYLON.serialize()
  42147. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  42148. __decorate([
  42149. BABYLON.serialize()
  42150. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  42151. __decorate([
  42152. BABYLON.serialize()
  42153. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  42154. return ArcRotateCameraPointersInput;
  42155. }());
  42156. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  42157. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  42158. })(BABYLON || (BABYLON = {}));
  42159. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  42160. var BABYLON;
  42161. (function (BABYLON) {
  42162. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  42163. __extends(ArcRotateCameraInputsManager, _super);
  42164. function ArcRotateCameraInputsManager(camera) {
  42165. return _super.call(this, camera) || this;
  42166. }
  42167. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  42168. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  42169. return this;
  42170. };
  42171. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  42172. this.add(new BABYLON.ArcRotateCameraPointersInput());
  42173. return this;
  42174. };
  42175. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  42176. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  42177. return this;
  42178. };
  42179. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  42180. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  42181. return this;
  42182. };
  42183. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  42184. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  42185. return this;
  42186. };
  42187. return ArcRotateCameraInputsManager;
  42188. }(BABYLON.CameraInputsManager));
  42189. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  42190. })(BABYLON || (BABYLON = {}));
  42191. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  42192. var BABYLON;
  42193. (function (BABYLON) {
  42194. var ArcRotateCamera = /** @class */ (function (_super) {
  42195. __extends(ArcRotateCamera, _super);
  42196. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  42197. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  42198. _this.inertialAlphaOffset = 0;
  42199. _this.inertialBetaOffset = 0;
  42200. _this.inertialRadiusOffset = 0;
  42201. _this.lowerAlphaLimit = null;
  42202. _this.upperAlphaLimit = null;
  42203. _this.lowerBetaLimit = 0.01;
  42204. _this.upperBetaLimit = Math.PI;
  42205. _this.lowerRadiusLimit = null;
  42206. _this.upperRadiusLimit = null;
  42207. _this.inertialPanningX = 0;
  42208. _this.inertialPanningY = 0;
  42209. _this.pinchToPanMaxDistance = 20;
  42210. _this.panningDistanceLimit = null;
  42211. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  42212. _this.panningInertia = 0.9;
  42213. //-- end properties for backward compatibility for inputs
  42214. _this.zoomOnFactor = 1;
  42215. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  42216. _this.allowUpsideDown = true;
  42217. _this._viewMatrix = new BABYLON.Matrix();
  42218. // Panning
  42219. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  42220. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  42221. _this.checkCollisions = false;
  42222. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42223. _this._previousPosition = BABYLON.Vector3.Zero();
  42224. _this._collisionVelocity = BABYLON.Vector3.Zero();
  42225. _this._newPosition = BABYLON.Vector3.Zero();
  42226. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42227. if (collidedMesh === void 0) { collidedMesh = null; }
  42228. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  42229. newPosition.multiplyInPlace(_this._collider._radius);
  42230. }
  42231. if (!collidedMesh) {
  42232. _this._previousPosition.copyFrom(_this.position);
  42233. }
  42234. else {
  42235. _this.setPosition(newPosition);
  42236. if (_this.onCollide) {
  42237. _this.onCollide(collidedMesh);
  42238. }
  42239. }
  42240. // Recompute because of constraints
  42241. var cosa = Math.cos(_this.alpha);
  42242. var sina = Math.sin(_this.alpha);
  42243. var cosb = Math.cos(_this.beta);
  42244. var sinb = Math.sin(_this.beta);
  42245. if (sinb === 0) {
  42246. sinb = 0.0001;
  42247. }
  42248. var target = _this._getTargetPosition();
  42249. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  42250. _this.position.copyFrom(_this._newPosition);
  42251. var up = _this.upVector;
  42252. if (_this.allowUpsideDown && _this.beta < 0) {
  42253. up = up.clone();
  42254. up = up.negate();
  42255. }
  42256. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  42257. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  42258. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  42259. _this._collisionTriggered = false;
  42260. };
  42261. _this._target = BABYLON.Vector3.Zero();
  42262. if (target) {
  42263. _this.setTarget(target);
  42264. }
  42265. _this.alpha = alpha;
  42266. _this.beta = beta;
  42267. _this.radius = radius;
  42268. _this.getViewMatrix();
  42269. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  42270. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  42271. return _this;
  42272. }
  42273. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  42274. get: function () {
  42275. return this._target;
  42276. },
  42277. set: function (value) {
  42278. this.setTarget(value);
  42279. },
  42280. enumerable: true,
  42281. configurable: true
  42282. });
  42283. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  42284. //-- begin properties for backward compatibility for inputs
  42285. get: function () {
  42286. var pointers = this.inputs.attached["pointers"];
  42287. if (pointers)
  42288. return pointers.angularSensibilityX;
  42289. return 0;
  42290. },
  42291. set: function (value) {
  42292. var pointers = this.inputs.attached["pointers"];
  42293. if (pointers) {
  42294. pointers.angularSensibilityX = value;
  42295. }
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  42301. get: function () {
  42302. var pointers = this.inputs.attached["pointers"];
  42303. if (pointers)
  42304. return pointers.angularSensibilityY;
  42305. return 0;
  42306. },
  42307. set: function (value) {
  42308. var pointers = this.inputs.attached["pointers"];
  42309. if (pointers) {
  42310. pointers.angularSensibilityY = value;
  42311. }
  42312. },
  42313. enumerable: true,
  42314. configurable: true
  42315. });
  42316. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  42317. get: function () {
  42318. var pointers = this.inputs.attached["pointers"];
  42319. if (pointers)
  42320. return pointers.pinchPrecision;
  42321. return 0;
  42322. },
  42323. set: function (value) {
  42324. var pointers = this.inputs.attached["pointers"];
  42325. if (pointers) {
  42326. pointers.pinchPrecision = value;
  42327. }
  42328. },
  42329. enumerable: true,
  42330. configurable: true
  42331. });
  42332. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  42333. get: function () {
  42334. var pointers = this.inputs.attached["pointers"];
  42335. if (pointers)
  42336. return pointers.pinchDeltaPercentage;
  42337. return 0;
  42338. },
  42339. set: function (value) {
  42340. var pointers = this.inputs.attached["pointers"];
  42341. if (pointers) {
  42342. pointers.pinchDeltaPercentage = value;
  42343. }
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  42349. get: function () {
  42350. var pointers = this.inputs.attached["pointers"];
  42351. if (pointers)
  42352. return pointers.panningSensibility;
  42353. return 0;
  42354. },
  42355. set: function (value) {
  42356. var pointers = this.inputs.attached["pointers"];
  42357. if (pointers) {
  42358. pointers.panningSensibility = value;
  42359. }
  42360. },
  42361. enumerable: true,
  42362. configurable: true
  42363. });
  42364. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  42365. get: function () {
  42366. var keyboard = this.inputs.attached["keyboard"];
  42367. if (keyboard)
  42368. return keyboard.keysUp;
  42369. return [];
  42370. },
  42371. set: function (value) {
  42372. var keyboard = this.inputs.attached["keyboard"];
  42373. if (keyboard)
  42374. keyboard.keysUp = value;
  42375. },
  42376. enumerable: true,
  42377. configurable: true
  42378. });
  42379. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  42380. get: function () {
  42381. var keyboard = this.inputs.attached["keyboard"];
  42382. if (keyboard)
  42383. return keyboard.keysDown;
  42384. return [];
  42385. },
  42386. set: function (value) {
  42387. var keyboard = this.inputs.attached["keyboard"];
  42388. if (keyboard)
  42389. keyboard.keysDown = value;
  42390. },
  42391. enumerable: true,
  42392. configurable: true
  42393. });
  42394. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  42395. get: function () {
  42396. var keyboard = this.inputs.attached["keyboard"];
  42397. if (keyboard)
  42398. return keyboard.keysLeft;
  42399. return [];
  42400. },
  42401. set: function (value) {
  42402. var keyboard = this.inputs.attached["keyboard"];
  42403. if (keyboard)
  42404. keyboard.keysLeft = value;
  42405. },
  42406. enumerable: true,
  42407. configurable: true
  42408. });
  42409. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  42410. get: function () {
  42411. var keyboard = this.inputs.attached["keyboard"];
  42412. if (keyboard)
  42413. return keyboard.keysRight;
  42414. return [];
  42415. },
  42416. set: function (value) {
  42417. var keyboard = this.inputs.attached["keyboard"];
  42418. if (keyboard)
  42419. keyboard.keysRight = value;
  42420. },
  42421. enumerable: true,
  42422. configurable: true
  42423. });
  42424. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42425. get: function () {
  42426. var mousewheel = this.inputs.attached["mousewheel"];
  42427. if (mousewheel)
  42428. return mousewheel.wheelPrecision;
  42429. return 0;
  42430. },
  42431. set: function (value) {
  42432. var mousewheel = this.inputs.attached["mousewheel"];
  42433. if (mousewheel)
  42434. mousewheel.wheelPrecision = value;
  42435. },
  42436. enumerable: true,
  42437. configurable: true
  42438. });
  42439. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42440. get: function () {
  42441. var mousewheel = this.inputs.attached["mousewheel"];
  42442. if (mousewheel)
  42443. return mousewheel.wheelDeltaPercentage;
  42444. return 0;
  42445. },
  42446. set: function (value) {
  42447. var mousewheel = this.inputs.attached["mousewheel"];
  42448. if (mousewheel)
  42449. mousewheel.wheelDeltaPercentage = value;
  42450. },
  42451. enumerable: true,
  42452. configurable: true
  42453. });
  42454. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42455. get: function () {
  42456. return this._bouncingBehavior;
  42457. },
  42458. enumerable: true,
  42459. configurable: true
  42460. });
  42461. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42462. get: function () {
  42463. return this._bouncingBehavior != null;
  42464. },
  42465. set: function (value) {
  42466. if (value === this.useBouncingBehavior) {
  42467. return;
  42468. }
  42469. if (value) {
  42470. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42471. this.addBehavior(this._bouncingBehavior);
  42472. }
  42473. else if (this._bouncingBehavior) {
  42474. this.removeBehavior(this._bouncingBehavior);
  42475. this._bouncingBehavior = null;
  42476. }
  42477. },
  42478. enumerable: true,
  42479. configurable: true
  42480. });
  42481. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42482. get: function () {
  42483. return this._framingBehavior;
  42484. },
  42485. enumerable: true,
  42486. configurable: true
  42487. });
  42488. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42489. get: function () {
  42490. return this._framingBehavior != null;
  42491. },
  42492. set: function (value) {
  42493. if (value === this.useFramingBehavior) {
  42494. return;
  42495. }
  42496. if (value) {
  42497. this._framingBehavior = new BABYLON.FramingBehavior();
  42498. this.addBehavior(this._framingBehavior);
  42499. }
  42500. else if (this._framingBehavior) {
  42501. this.removeBehavior(this._framingBehavior);
  42502. this._framingBehavior = null;
  42503. }
  42504. },
  42505. enumerable: true,
  42506. configurable: true
  42507. });
  42508. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42509. get: function () {
  42510. return this._autoRotationBehavior;
  42511. },
  42512. enumerable: true,
  42513. configurable: true
  42514. });
  42515. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42516. get: function () {
  42517. return this._autoRotationBehavior != null;
  42518. },
  42519. set: function (value) {
  42520. if (value === this.useAutoRotationBehavior) {
  42521. return;
  42522. }
  42523. if (value) {
  42524. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42525. this.addBehavior(this._autoRotationBehavior);
  42526. }
  42527. else if (this._autoRotationBehavior) {
  42528. this.removeBehavior(this._autoRotationBehavior);
  42529. this._autoRotationBehavior = null;
  42530. }
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. // Cache
  42536. ArcRotateCamera.prototype._initCache = function () {
  42537. _super.prototype._initCache.call(this);
  42538. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42539. this._cache.alpha = undefined;
  42540. this._cache.beta = undefined;
  42541. this._cache.radius = undefined;
  42542. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42543. };
  42544. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42545. if (!ignoreParentClass) {
  42546. _super.prototype._updateCache.call(this);
  42547. }
  42548. this._cache._target.copyFrom(this._getTargetPosition());
  42549. this._cache.alpha = this.alpha;
  42550. this._cache.beta = this.beta;
  42551. this._cache.radius = this.radius;
  42552. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42553. };
  42554. ArcRotateCamera.prototype._getTargetPosition = function () {
  42555. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42556. var pos = this._targetHost.getAbsolutePosition();
  42557. if (this._targetBoundingCenter) {
  42558. pos.addToRef(this._targetBoundingCenter, this._target);
  42559. }
  42560. else {
  42561. this._target.copyFrom(pos);
  42562. }
  42563. }
  42564. var lockedTargetPosition = this._getLockedTargetPosition();
  42565. if (lockedTargetPosition) {
  42566. return lockedTargetPosition;
  42567. }
  42568. return this._target;
  42569. };
  42570. ArcRotateCamera.prototype.storeState = function () {
  42571. this._storedAlpha = this.alpha;
  42572. this._storedBeta = this.beta;
  42573. this._storedRadius = this.radius;
  42574. this._storedTarget = this._getTargetPosition().clone();
  42575. return _super.prototype.storeState.call(this);
  42576. };
  42577. /**
  42578. * Restored camera state. You must call storeState() first
  42579. */
  42580. ArcRotateCamera.prototype._restoreStateValues = function () {
  42581. if (!_super.prototype._restoreStateValues.call(this)) {
  42582. return false;
  42583. }
  42584. this.alpha = this._storedAlpha;
  42585. this.beta = this._storedBeta;
  42586. this.radius = this._storedRadius;
  42587. this.setTarget(this._storedTarget.clone());
  42588. this.inertialAlphaOffset = 0;
  42589. this.inertialBetaOffset = 0;
  42590. this.inertialRadiusOffset = 0;
  42591. this.inertialPanningX = 0;
  42592. this.inertialPanningY = 0;
  42593. return true;
  42594. };
  42595. // Synchronized
  42596. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42597. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42598. return false;
  42599. return this._cache._target.equals(this._getTargetPosition())
  42600. && this._cache.alpha === this.alpha
  42601. && this._cache.beta === this.beta
  42602. && this._cache.radius === this.radius
  42603. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42604. };
  42605. // Methods
  42606. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42607. var _this = this;
  42608. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42609. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42610. this._useCtrlForPanning = useCtrlForPanning;
  42611. this._panningMouseButton = panningMouseButton;
  42612. this.inputs.attachElement(element, noPreventDefault);
  42613. this._reset = function () {
  42614. _this.inertialAlphaOffset = 0;
  42615. _this.inertialBetaOffset = 0;
  42616. _this.inertialRadiusOffset = 0;
  42617. _this.inertialPanningX = 0;
  42618. _this.inertialPanningY = 0;
  42619. };
  42620. };
  42621. ArcRotateCamera.prototype.detachControl = function (element) {
  42622. this.inputs.detachElement(element);
  42623. if (this._reset) {
  42624. this._reset();
  42625. }
  42626. };
  42627. ArcRotateCamera.prototype._checkInputs = function () {
  42628. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42629. if (this._collisionTriggered) {
  42630. return;
  42631. }
  42632. this.inputs.checkInputs();
  42633. // Inertia
  42634. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42635. if (this.getScene().useRightHandedSystem) {
  42636. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42637. }
  42638. else {
  42639. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42640. }
  42641. this.beta += this.inertialBetaOffset;
  42642. this.radius -= this.inertialRadiusOffset;
  42643. this.inertialAlphaOffset *= this.inertia;
  42644. this.inertialBetaOffset *= this.inertia;
  42645. this.inertialRadiusOffset *= this.inertia;
  42646. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42647. this.inertialAlphaOffset = 0;
  42648. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42649. this.inertialBetaOffset = 0;
  42650. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42651. this.inertialRadiusOffset = 0;
  42652. }
  42653. // Panning inertia
  42654. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42655. if (!this._localDirection) {
  42656. this._localDirection = BABYLON.Vector3.Zero();
  42657. this._transformedDirection = BABYLON.Vector3.Zero();
  42658. }
  42659. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42660. this._localDirection.multiplyInPlace(this.panningAxis);
  42661. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42662. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42663. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42664. if (!this.panningAxis.y) {
  42665. this._transformedDirection.y = 0;
  42666. }
  42667. if (!this._targetHost) {
  42668. if (this.panningDistanceLimit) {
  42669. this._transformedDirection.addInPlace(this._target);
  42670. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42671. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42672. this._target.copyFrom(this._transformedDirection);
  42673. }
  42674. }
  42675. else {
  42676. this._target.addInPlace(this._transformedDirection);
  42677. }
  42678. }
  42679. this.inertialPanningX *= this.panningInertia;
  42680. this.inertialPanningY *= this.panningInertia;
  42681. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42682. this.inertialPanningX = 0;
  42683. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42684. this.inertialPanningY = 0;
  42685. }
  42686. // Limits
  42687. this._checkLimits();
  42688. _super.prototype._checkInputs.call(this);
  42689. };
  42690. ArcRotateCamera.prototype._checkLimits = function () {
  42691. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42692. if (this.allowUpsideDown && this.beta > Math.PI) {
  42693. this.beta = this.beta - (2 * Math.PI);
  42694. }
  42695. }
  42696. else {
  42697. if (this.beta < this.lowerBetaLimit) {
  42698. this.beta = this.lowerBetaLimit;
  42699. }
  42700. }
  42701. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42702. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42703. this.beta = this.beta + (2 * Math.PI);
  42704. }
  42705. }
  42706. else {
  42707. if (this.beta > this.upperBetaLimit) {
  42708. this.beta = this.upperBetaLimit;
  42709. }
  42710. }
  42711. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42712. this.alpha = this.lowerAlphaLimit;
  42713. }
  42714. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42715. this.alpha = this.upperAlphaLimit;
  42716. }
  42717. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42718. this.radius = this.lowerRadiusLimit;
  42719. }
  42720. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42721. this.radius = this.upperRadiusLimit;
  42722. }
  42723. };
  42724. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42725. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42726. this.radius = radiusv3.length();
  42727. if (this.radius === 0) {
  42728. this.radius = 0.0001; // Just to avoid division by zero
  42729. }
  42730. // Alpha
  42731. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42732. if (radiusv3.z < 0) {
  42733. this.alpha = 2 * Math.PI - this.alpha;
  42734. }
  42735. // Beta
  42736. this.beta = Math.acos(radiusv3.y / this.radius);
  42737. this._checkLimits();
  42738. };
  42739. ArcRotateCamera.prototype.setPosition = function (position) {
  42740. if (this.position.equals(position)) {
  42741. return;
  42742. }
  42743. this.position.copyFrom(position);
  42744. this.rebuildAnglesAndRadius();
  42745. };
  42746. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42747. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42748. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42749. if (target.getBoundingInfo) {
  42750. if (toBoundingCenter) {
  42751. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42752. }
  42753. else {
  42754. this._targetBoundingCenter = null;
  42755. }
  42756. this._targetHost = target;
  42757. this._target = this._getTargetPosition();
  42758. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42759. }
  42760. else {
  42761. var newTarget = target;
  42762. var currentTarget = this._getTargetPosition();
  42763. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42764. return;
  42765. }
  42766. this._targetHost = null;
  42767. this._target = newTarget;
  42768. this._targetBoundingCenter = null;
  42769. this.onMeshTargetChangedObservable.notifyObservers(null);
  42770. }
  42771. this.rebuildAnglesAndRadius();
  42772. };
  42773. ArcRotateCamera.prototype._getViewMatrix = function () {
  42774. // Compute
  42775. var cosa = Math.cos(this.alpha);
  42776. var sina = Math.sin(this.alpha);
  42777. var cosb = Math.cos(this.beta);
  42778. var sinb = Math.sin(this.beta);
  42779. if (sinb === 0) {
  42780. sinb = 0.0001;
  42781. }
  42782. var target = this._getTargetPosition();
  42783. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42784. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42785. if (!this._collider) {
  42786. this._collider = new BABYLON.Collider();
  42787. }
  42788. this._collider._radius = this.collisionRadius;
  42789. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42790. this._collisionTriggered = true;
  42791. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42792. }
  42793. else {
  42794. this.position.copyFrom(this._newPosition);
  42795. var up = this.upVector;
  42796. if (this.allowUpsideDown && sinb < 0) {
  42797. up = up.clone();
  42798. up = up.negate();
  42799. }
  42800. if (this.getScene().useRightHandedSystem) {
  42801. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42802. }
  42803. else {
  42804. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42805. }
  42806. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42807. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42808. }
  42809. this._currentTarget = target;
  42810. return this._viewMatrix;
  42811. };
  42812. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42813. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42814. meshes = meshes || this.getScene().meshes;
  42815. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42816. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42817. this.radius = distance * this.zoomOnFactor;
  42818. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42819. };
  42820. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42821. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42822. var meshesOrMinMaxVector;
  42823. var distance;
  42824. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42825. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42826. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42827. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42828. }
  42829. else {
  42830. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42831. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42832. distance = minMaxVectorAndDistance.distance;
  42833. }
  42834. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42835. if (!doNotUpdateMaxZ) {
  42836. this.maxZ = distance * 2;
  42837. }
  42838. };
  42839. /**
  42840. * @override
  42841. * Override Camera.createRigCamera
  42842. */
  42843. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42844. var alphaShift = 0;
  42845. switch (this.cameraRigMode) {
  42846. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42847. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42848. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42849. case BABYLON.Camera.RIG_MODE_VR:
  42850. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42851. break;
  42852. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42853. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42854. break;
  42855. }
  42856. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42857. rigCam._cameraRigParams = {};
  42858. return rigCam;
  42859. };
  42860. /**
  42861. * @override
  42862. * Override Camera._updateRigCameras
  42863. */
  42864. ArcRotateCamera.prototype._updateRigCameras = function () {
  42865. var camLeft = this._rigCameras[0];
  42866. var camRight = this._rigCameras[1];
  42867. camLeft.beta = camRight.beta = this.beta;
  42868. camLeft.radius = camRight.radius = this.radius;
  42869. switch (this.cameraRigMode) {
  42870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42871. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42872. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42873. case BABYLON.Camera.RIG_MODE_VR:
  42874. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42875. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42876. break;
  42877. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42878. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42879. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42880. break;
  42881. }
  42882. _super.prototype._updateRigCameras.call(this);
  42883. };
  42884. ArcRotateCamera.prototype.dispose = function () {
  42885. this.inputs.clear();
  42886. _super.prototype.dispose.call(this);
  42887. };
  42888. ArcRotateCamera.prototype.getClassName = function () {
  42889. return "ArcRotateCamera";
  42890. };
  42891. __decorate([
  42892. BABYLON.serialize()
  42893. ], ArcRotateCamera.prototype, "alpha", void 0);
  42894. __decorate([
  42895. BABYLON.serialize()
  42896. ], ArcRotateCamera.prototype, "beta", void 0);
  42897. __decorate([
  42898. BABYLON.serialize()
  42899. ], ArcRotateCamera.prototype, "radius", void 0);
  42900. __decorate([
  42901. BABYLON.serializeAsVector3("target")
  42902. ], ArcRotateCamera.prototype, "_target", void 0);
  42903. __decorate([
  42904. BABYLON.serialize()
  42905. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42906. __decorate([
  42907. BABYLON.serialize()
  42908. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42909. __decorate([
  42910. BABYLON.serialize()
  42911. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42912. __decorate([
  42913. BABYLON.serialize()
  42914. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42915. __decorate([
  42916. BABYLON.serialize()
  42917. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42918. __decorate([
  42919. BABYLON.serialize()
  42920. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42921. __decorate([
  42922. BABYLON.serialize()
  42923. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42924. __decorate([
  42925. BABYLON.serialize()
  42926. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42927. __decorate([
  42928. BABYLON.serialize()
  42929. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42930. __decorate([
  42931. BABYLON.serialize()
  42932. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42933. __decorate([
  42934. BABYLON.serialize()
  42935. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42936. __decorate([
  42937. BABYLON.serialize()
  42938. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42939. __decorate([
  42940. BABYLON.serialize()
  42941. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42942. __decorate([
  42943. BABYLON.serializeAsVector3()
  42944. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42945. __decorate([
  42946. BABYLON.serialize()
  42947. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42948. __decorate([
  42949. BABYLON.serialize()
  42950. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42951. __decorate([
  42952. BABYLON.serialize()
  42953. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42954. return ArcRotateCamera;
  42955. }(BABYLON.TargetCamera));
  42956. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42957. })(BABYLON || (BABYLON = {}));
  42958. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42959. var BABYLON;
  42960. (function (BABYLON) {
  42961. /**
  42962. * The HemisphericLight simulates the ambient environment light,
  42963. * so the passed direction is the light reflection direction, not the incoming direction.
  42964. */
  42965. var HemisphericLight = /** @class */ (function (_super) {
  42966. __extends(HemisphericLight, _super);
  42967. /**
  42968. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42969. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42970. * The HemisphericLight can't cast shadows.
  42971. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42972. * @param name The friendly name of the light
  42973. * @param direction The direction of the light reflection
  42974. * @param scene The scene the light belongs to
  42975. */
  42976. function HemisphericLight(name, direction, scene) {
  42977. var _this = _super.call(this, name, scene) || this;
  42978. /**
  42979. * The groundColor is the light in the opposite direction to the one specified during creation.
  42980. * 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.
  42981. */
  42982. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42983. _this.direction = direction || BABYLON.Vector3.Up();
  42984. return _this;
  42985. }
  42986. HemisphericLight.prototype._buildUniformLayout = function () {
  42987. this._uniformBuffer.addUniform("vLightData", 4);
  42988. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42989. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42990. this._uniformBuffer.addUniform("vLightGround", 3);
  42991. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42992. this._uniformBuffer.addUniform("depthValues", 2);
  42993. this._uniformBuffer.create();
  42994. };
  42995. /**
  42996. * Returns the string "HemisphericLight".
  42997. * @return The class name
  42998. */
  42999. HemisphericLight.prototype.getClassName = function () {
  43000. return "HemisphericLight";
  43001. };
  43002. /**
  43003. * Sets the HemisphericLight direction towards the passed target (Vector3).
  43004. * Returns the updated direction.
  43005. * @param target The target the direction should point to
  43006. * @return The computed direction
  43007. */
  43008. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  43009. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  43010. return this.direction;
  43011. };
  43012. /**
  43013. * Returns the shadow generator associated to the light.
  43014. * @returns Always null for hemispheric lights because it does not support shadows.
  43015. */
  43016. HemisphericLight.prototype.getShadowGenerator = function () {
  43017. return null;
  43018. };
  43019. /**
  43020. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  43021. * @param effect The effect to update
  43022. * @param lightIndex The index of the light in the effect to update
  43023. * @returns The hemispheric light
  43024. */
  43025. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  43026. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43027. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  43028. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  43029. return this;
  43030. };
  43031. /**
  43032. * @ignore internal use only.
  43033. */
  43034. HemisphericLight.prototype._getWorldMatrix = function () {
  43035. if (!this._worldMatrix) {
  43036. this._worldMatrix = BABYLON.Matrix.Identity();
  43037. }
  43038. return this._worldMatrix;
  43039. };
  43040. /**
  43041. * Returns the integer 3.
  43042. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43043. */
  43044. HemisphericLight.prototype.getTypeID = function () {
  43045. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  43046. };
  43047. __decorate([
  43048. BABYLON.serializeAsColor3()
  43049. ], HemisphericLight.prototype, "groundColor", void 0);
  43050. __decorate([
  43051. BABYLON.serializeAsVector3()
  43052. ], HemisphericLight.prototype, "direction", void 0);
  43053. return HemisphericLight;
  43054. }(BABYLON.Light));
  43055. BABYLON.HemisphericLight = HemisphericLight;
  43056. })(BABYLON || (BABYLON = {}));
  43057. //# sourceMappingURL=babylon.hemisphericLight.js.map
  43058. var BABYLON;
  43059. (function (BABYLON) {
  43060. /**
  43061. * Base implementation of @see IShadowLight
  43062. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  43063. */
  43064. var ShadowLight = /** @class */ (function (_super) {
  43065. __extends(ShadowLight, _super);
  43066. function ShadowLight() {
  43067. var _this = _super !== null && _super.apply(this, arguments) || this;
  43068. _this._needProjectionMatrixCompute = true;
  43069. return _this;
  43070. }
  43071. ShadowLight.prototype._setPosition = function (value) {
  43072. this._position = value;
  43073. };
  43074. Object.defineProperty(ShadowLight.prototype, "position", {
  43075. /**
  43076. * Sets the position the shadow will be casted from. Also use as the light position for both
  43077. * point and spot lights.
  43078. */
  43079. get: function () {
  43080. return this._position;
  43081. },
  43082. /**
  43083. * Sets the position the shadow will be casted from. Also use as the light position for both
  43084. * point and spot lights.
  43085. */
  43086. set: function (value) {
  43087. this._setPosition(value);
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. ShadowLight.prototype._setDirection = function (value) {
  43093. this._direction = value;
  43094. };
  43095. Object.defineProperty(ShadowLight.prototype, "direction", {
  43096. /**
  43097. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  43098. * Also use as the light direction on spot and directional lights.
  43099. */
  43100. get: function () {
  43101. return this._direction;
  43102. },
  43103. /**
  43104. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  43105. * Also use as the light direction on spot and directional lights.
  43106. */
  43107. set: function (value) {
  43108. this._setDirection(value);
  43109. },
  43110. enumerable: true,
  43111. configurable: true
  43112. });
  43113. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  43114. /**
  43115. * Gets the shadow projection clipping minimum z value.
  43116. */
  43117. get: function () {
  43118. return this._shadowMinZ;
  43119. },
  43120. /**
  43121. * Sets the shadow projection clipping minimum z value.
  43122. */
  43123. set: function (value) {
  43124. this._shadowMinZ = value;
  43125. this.forceProjectionMatrixCompute();
  43126. },
  43127. enumerable: true,
  43128. configurable: true
  43129. });
  43130. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  43131. /**
  43132. * Sets the shadow projection clipping maximum z value.
  43133. */
  43134. get: function () {
  43135. return this._shadowMaxZ;
  43136. },
  43137. /**
  43138. * Gets the shadow projection clipping maximum z value.
  43139. */
  43140. set: function (value) {
  43141. this._shadowMaxZ = value;
  43142. this.forceProjectionMatrixCompute();
  43143. },
  43144. enumerable: true,
  43145. configurable: true
  43146. });
  43147. /**
  43148. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  43149. * @returns true if the information has been computed, false if it does not need to (no parenting)
  43150. */
  43151. ShadowLight.prototype.computeTransformedInformation = function () {
  43152. if (this.parent && this.parent.getWorldMatrix) {
  43153. if (!this.transformedPosition) {
  43154. this.transformedPosition = BABYLON.Vector3.Zero();
  43155. }
  43156. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  43157. // In case the direction is present.
  43158. if (this.direction) {
  43159. if (!this.transformedDirection) {
  43160. this.transformedDirection = BABYLON.Vector3.Zero();
  43161. }
  43162. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  43163. }
  43164. return true;
  43165. }
  43166. return false;
  43167. };
  43168. /**
  43169. * Return the depth scale used for the shadow map.
  43170. * @returns the depth scale.
  43171. */
  43172. ShadowLight.prototype.getDepthScale = function () {
  43173. return 50.0;
  43174. };
  43175. /**
  43176. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  43177. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43178. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43179. */
  43180. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  43181. return this.transformedDirection ? this.transformedDirection : this.direction;
  43182. };
  43183. /**
  43184. * Returns the ShadowLight absolute position in the World.
  43185. * @returns the position vector in world space
  43186. */
  43187. ShadowLight.prototype.getAbsolutePosition = function () {
  43188. return this.transformedPosition ? this.transformedPosition : this.position;
  43189. };
  43190. /**
  43191. * Sets the ShadowLight direction toward the passed target.
  43192. * @param target The point tot target in local space
  43193. * @returns the updated ShadowLight direction
  43194. */
  43195. ShadowLight.prototype.setDirectionToTarget = function (target) {
  43196. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  43197. return this.direction;
  43198. };
  43199. /**
  43200. * Returns the light rotation in euler definition.
  43201. * @returns the x y z rotation in local space.
  43202. */
  43203. ShadowLight.prototype.getRotation = function () {
  43204. this.direction.normalize();
  43205. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  43206. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  43207. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  43208. };
  43209. /**
  43210. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  43211. * @returns true if a cube texture needs to be use
  43212. */
  43213. ShadowLight.prototype.needCube = function () {
  43214. return false;
  43215. };
  43216. /**
  43217. * Detects if the projection matrix requires to be recomputed this frame.
  43218. * @returns true if it requires to be recomputed otherwise, false.
  43219. */
  43220. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  43221. return this._needProjectionMatrixCompute;
  43222. };
  43223. /**
  43224. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  43225. */
  43226. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  43227. this._needProjectionMatrixCompute = true;
  43228. };
  43229. /**
  43230. * Get the world matrix of the sahdow lights.
  43231. * @ignore Internal Use Only
  43232. */
  43233. ShadowLight.prototype._getWorldMatrix = function () {
  43234. if (!this._worldMatrix) {
  43235. this._worldMatrix = BABYLON.Matrix.Identity();
  43236. }
  43237. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  43238. return this._worldMatrix;
  43239. };
  43240. /**
  43241. * Gets the minZ used for shadow according to both the scene and the light.
  43242. * @param activeCamera The camera we are returning the min for
  43243. * @returns the depth min z
  43244. */
  43245. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  43246. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  43247. };
  43248. /**
  43249. * Gets the maxZ used for shadow according to both the scene and the light.
  43250. * @param activeCamera The camera we are returning the max for
  43251. * @returns the depth max z
  43252. */
  43253. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  43254. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  43255. };
  43256. /**
  43257. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  43258. * @param matrix The materix to updated with the projection information
  43259. * @param viewMatrix The transform matrix of the light
  43260. * @param renderList The list of mesh to render in the map
  43261. * @returns The current light
  43262. */
  43263. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43264. if (this.customProjectionMatrixBuilder) {
  43265. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  43266. }
  43267. else {
  43268. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43269. }
  43270. return this;
  43271. };
  43272. __decorate([
  43273. BABYLON.serializeAsVector3()
  43274. ], ShadowLight.prototype, "position", null);
  43275. __decorate([
  43276. BABYLON.serializeAsVector3()
  43277. ], ShadowLight.prototype, "direction", null);
  43278. __decorate([
  43279. BABYLON.serialize()
  43280. ], ShadowLight.prototype, "shadowMinZ", null);
  43281. __decorate([
  43282. BABYLON.serialize()
  43283. ], ShadowLight.prototype, "shadowMaxZ", null);
  43284. return ShadowLight;
  43285. }(BABYLON.Light));
  43286. BABYLON.ShadowLight = ShadowLight;
  43287. })(BABYLON || (BABYLON = {}));
  43288. //# sourceMappingURL=babylon.shadowLight.js.map
  43289. var BABYLON;
  43290. (function (BABYLON) {
  43291. /**
  43292. * A point light is a light defined by an unique point in world space.
  43293. * The light is emitted in every direction from this point.
  43294. * A good example of a point light is a standard light bulb.
  43295. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43296. */
  43297. var PointLight = /** @class */ (function (_super) {
  43298. __extends(PointLight, _super);
  43299. /**
  43300. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  43301. * A PointLight emits the light in every direction.
  43302. * It can cast shadows.
  43303. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  43304. * ```javascript
  43305. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  43306. * ```
  43307. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43308. * @param name The light friendly name
  43309. * @param position The position of the point light in the scene
  43310. * @param scene The scene the lights belongs to
  43311. */
  43312. function PointLight(name, position, scene) {
  43313. var _this = _super.call(this, name, scene) || this;
  43314. _this._shadowAngle = Math.PI / 2;
  43315. _this.position = position;
  43316. return _this;
  43317. }
  43318. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  43319. /**
  43320. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43321. * This specifies what angle the shadow will use to be created.
  43322. *
  43323. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43324. */
  43325. get: function () {
  43326. return this._shadowAngle;
  43327. },
  43328. /**
  43329. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43330. * This specifies what angle the shadow will use to be created.
  43331. *
  43332. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43333. */
  43334. set: function (value) {
  43335. this._shadowAngle = value;
  43336. this.forceProjectionMatrixCompute();
  43337. },
  43338. enumerable: true,
  43339. configurable: true
  43340. });
  43341. Object.defineProperty(PointLight.prototype, "direction", {
  43342. /**
  43343. * Gets the direction if it has been set.
  43344. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43345. */
  43346. get: function () {
  43347. return this._direction;
  43348. },
  43349. /**
  43350. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43351. */
  43352. set: function (value) {
  43353. var previousNeedCube = this.needCube();
  43354. this._direction = value;
  43355. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  43356. this._shadowGenerator.recreateShadowMap();
  43357. }
  43358. },
  43359. enumerable: true,
  43360. configurable: true
  43361. });
  43362. /**
  43363. * Returns the string "PointLight"
  43364. * @returns the class name
  43365. */
  43366. PointLight.prototype.getClassName = function () {
  43367. return "PointLight";
  43368. };
  43369. /**
  43370. * Returns the integer 0.
  43371. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43372. */
  43373. PointLight.prototype.getTypeID = function () {
  43374. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  43375. };
  43376. /**
  43377. * Specifies wether or not the shadowmap should be a cube texture.
  43378. * @returns true if the shadowmap needs to be a cube texture.
  43379. */
  43380. PointLight.prototype.needCube = function () {
  43381. return !this.direction;
  43382. };
  43383. /**
  43384. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  43385. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43386. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43387. */
  43388. PointLight.prototype.getShadowDirection = function (faceIndex) {
  43389. if (this.direction) {
  43390. return _super.prototype.getShadowDirection.call(this, faceIndex);
  43391. }
  43392. else {
  43393. switch (faceIndex) {
  43394. case 0:
  43395. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  43396. case 1:
  43397. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  43398. case 2:
  43399. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  43400. case 3:
  43401. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  43402. case 4:
  43403. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  43404. case 5:
  43405. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  43406. }
  43407. }
  43408. return BABYLON.Vector3.Zero();
  43409. };
  43410. /**
  43411. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  43412. * - fov = PI / 2
  43413. * - aspect ratio : 1.0
  43414. * - z-near and far equal to the active camera minZ and maxZ.
  43415. * Returns the PointLight.
  43416. */
  43417. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43418. var activeCamera = this.getScene().activeCamera;
  43419. if (!activeCamera) {
  43420. return;
  43421. }
  43422. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43423. };
  43424. PointLight.prototype._buildUniformLayout = function () {
  43425. this._uniformBuffer.addUniform("vLightData", 4);
  43426. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43427. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43428. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43429. this._uniformBuffer.addUniform("depthValues", 2);
  43430. this._uniformBuffer.create();
  43431. };
  43432. /**
  43433. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  43434. * @param effect The effect to update
  43435. * @param lightIndex The index of the light in the effect to update
  43436. * @returns The point light
  43437. */
  43438. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  43439. if (this.computeTransformedInformation()) {
  43440. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  43441. return this;
  43442. }
  43443. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  43444. return this;
  43445. };
  43446. __decorate([
  43447. BABYLON.serialize()
  43448. ], PointLight.prototype, "shadowAngle", null);
  43449. return PointLight;
  43450. }(BABYLON.ShadowLight));
  43451. BABYLON.PointLight = PointLight;
  43452. })(BABYLON || (BABYLON = {}));
  43453. //# sourceMappingURL=babylon.pointLight.js.map
  43454. var BABYLON;
  43455. (function (BABYLON) {
  43456. /**
  43457. * A directional light is defined by a direction (what a surprise!).
  43458. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  43459. * 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.
  43460. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43461. */
  43462. var DirectionalLight = /** @class */ (function (_super) {
  43463. __extends(DirectionalLight, _super);
  43464. /**
  43465. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  43466. * The directional light is emitted from everywhere in the given direction.
  43467. * It can cast shawdows.
  43468. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43469. * @param name The friendly name of the light
  43470. * @param direction The direction of the light
  43471. * @param scene The scene the light belongs to
  43472. */
  43473. function DirectionalLight(name, direction, scene) {
  43474. var _this = _super.call(this, name, scene) || this;
  43475. _this._shadowFrustumSize = 0;
  43476. _this._shadowOrthoScale = 0.5;
  43477. /**
  43478. * Automatically compute the projection matrix to best fit (including all the casters)
  43479. * on each frame.
  43480. */
  43481. _this.autoUpdateExtends = true;
  43482. // Cache
  43483. _this._orthoLeft = Number.MAX_VALUE;
  43484. _this._orthoRight = Number.MIN_VALUE;
  43485. _this._orthoTop = Number.MIN_VALUE;
  43486. _this._orthoBottom = Number.MAX_VALUE;
  43487. _this.position = direction.scale(-1.0);
  43488. _this.direction = direction;
  43489. return _this;
  43490. }
  43491. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  43492. /**
  43493. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  43494. */
  43495. get: function () {
  43496. return this._shadowFrustumSize;
  43497. },
  43498. /**
  43499. * Specifies a fix frustum size for the shadow generation.
  43500. */
  43501. set: function (value) {
  43502. this._shadowFrustumSize = value;
  43503. this.forceProjectionMatrixCompute();
  43504. },
  43505. enumerable: true,
  43506. configurable: true
  43507. });
  43508. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  43509. /**
  43510. * Gets the shadow projection scale against the optimal computed one.
  43511. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43512. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43513. */
  43514. get: function () {
  43515. return this._shadowOrthoScale;
  43516. },
  43517. /**
  43518. * Sets the shadow projection scale against the optimal computed one.
  43519. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43520. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43521. */
  43522. set: function (value) {
  43523. this._shadowOrthoScale = value;
  43524. this.forceProjectionMatrixCompute();
  43525. },
  43526. enumerable: true,
  43527. configurable: true
  43528. });
  43529. /**
  43530. * Returns the string "DirectionalLight".
  43531. * @return The class name
  43532. */
  43533. DirectionalLight.prototype.getClassName = function () {
  43534. return "DirectionalLight";
  43535. };
  43536. /**
  43537. * Returns the integer 1.
  43538. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43539. */
  43540. DirectionalLight.prototype.getTypeID = function () {
  43541. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  43542. };
  43543. /**
  43544. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  43545. * Returns the DirectionalLight Shadow projection matrix.
  43546. */
  43547. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43548. if (this.shadowFrustumSize > 0) {
  43549. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43550. }
  43551. else {
  43552. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43553. }
  43554. };
  43555. /**
  43556. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43557. * Returns the DirectionalLight Shadow projection matrix.
  43558. */
  43559. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43560. var activeCamera = this.getScene().activeCamera;
  43561. if (!activeCamera) {
  43562. return;
  43563. }
  43564. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43565. };
  43566. /**
  43567. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43568. * Returns the DirectionalLight Shadow projection matrix.
  43569. */
  43570. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43571. var activeCamera = this.getScene().activeCamera;
  43572. if (!activeCamera) {
  43573. return;
  43574. }
  43575. // Check extends
  43576. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43577. var tempVector3 = BABYLON.Vector3.Zero();
  43578. this._orthoLeft = Number.MAX_VALUE;
  43579. this._orthoRight = Number.MIN_VALUE;
  43580. this._orthoTop = Number.MIN_VALUE;
  43581. this._orthoBottom = Number.MAX_VALUE;
  43582. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43583. var mesh = renderList[meshIndex];
  43584. if (!mesh) {
  43585. continue;
  43586. }
  43587. var boundingInfo = mesh.getBoundingInfo();
  43588. var boundingBox = boundingInfo.boundingBox;
  43589. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43590. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43591. if (tempVector3.x < this._orthoLeft)
  43592. this._orthoLeft = tempVector3.x;
  43593. if (tempVector3.y < this._orthoBottom)
  43594. this._orthoBottom = tempVector3.y;
  43595. if (tempVector3.x > this._orthoRight)
  43596. this._orthoRight = tempVector3.x;
  43597. if (tempVector3.y > this._orthoTop)
  43598. this._orthoTop = tempVector3.y;
  43599. }
  43600. }
  43601. }
  43602. var xOffset = this._orthoRight - this._orthoLeft;
  43603. var yOffset = this._orthoTop - this._orthoBottom;
  43604. 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);
  43605. };
  43606. DirectionalLight.prototype._buildUniformLayout = function () {
  43607. this._uniformBuffer.addUniform("vLightData", 4);
  43608. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43609. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43610. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43611. this._uniformBuffer.addUniform("depthValues", 2);
  43612. this._uniformBuffer.create();
  43613. };
  43614. /**
  43615. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43616. * @param effect The effect to update
  43617. * @param lightIndex The index of the light in the effect to update
  43618. * @returns The directional light
  43619. */
  43620. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43621. if (this.computeTransformedInformation()) {
  43622. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43623. return this;
  43624. }
  43625. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43626. return this;
  43627. };
  43628. /**
  43629. * Gets the minZ used for shadow according to both the scene and the light.
  43630. *
  43631. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43632. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43633. * @param activeCamera The camera we are returning the min for
  43634. * @returns the depth min z
  43635. */
  43636. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43637. return 1;
  43638. };
  43639. /**
  43640. * Gets the maxZ used for shadow according to both the scene and the light.
  43641. *
  43642. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43643. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43644. * @param activeCamera The camera we are returning the max for
  43645. * @returns the depth max z
  43646. */
  43647. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43648. return 1;
  43649. };
  43650. __decorate([
  43651. BABYLON.serialize()
  43652. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43653. __decorate([
  43654. BABYLON.serialize()
  43655. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43656. __decorate([
  43657. BABYLON.serialize()
  43658. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43659. return DirectionalLight;
  43660. }(BABYLON.ShadowLight));
  43661. BABYLON.DirectionalLight = DirectionalLight;
  43662. })(BABYLON || (BABYLON = {}));
  43663. //# sourceMappingURL=babylon.directionalLight.js.map
  43664. var BABYLON;
  43665. (function (BABYLON) {
  43666. /**
  43667. * A spot light is defined by a position, a direction, an angle, and an exponent.
  43668. * These values define a cone of light starting from the position, emitting toward the direction.
  43669. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  43670. * and the exponent defines the speed of the decay of the light with distance (reach).
  43671. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43672. */
  43673. var SpotLight = /** @class */ (function (_super) {
  43674. __extends(SpotLight, _super);
  43675. /**
  43676. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  43677. * It can cast shadows.
  43678. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43679. * @param name The light friendly name
  43680. * @param position The position of the spot light in the scene
  43681. * @param direction The direction of the light in the scene
  43682. * @param angle The cone angle of the light in Radians
  43683. * @param exponent The light decay speed with the distance from the emission spot
  43684. * @param scene The scene the lights belongs to
  43685. */
  43686. function SpotLight(name, position, direction, angle, exponent, scene) {
  43687. var _this = _super.call(this, name, scene) || this;
  43688. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  43689. _this._projectionTextureLightNear = 1e-6;
  43690. _this._projectionTextureLightFar = 1000.0;
  43691. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  43692. _this._projectionTextureViewLightDirty = true;
  43693. _this._projectionTextureProjectionLightDirty = true;
  43694. _this._projectionTextureDirty = true;
  43695. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  43696. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  43697. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  43698. _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);
  43699. _this.position = position;
  43700. _this.direction = direction;
  43701. _this.angle = angle;
  43702. _this.exponent = exponent;
  43703. return _this;
  43704. }
  43705. Object.defineProperty(SpotLight.prototype, "angle", {
  43706. /**
  43707. * Gets the cone angle of the spot light in Radians.
  43708. */
  43709. get: function () {
  43710. return this._angle;
  43711. },
  43712. /**
  43713. * Sets the cone angle of the spot light in Radians.
  43714. */
  43715. set: function (value) {
  43716. this._angle = value;
  43717. this._projectionTextureProjectionLightDirty = true;
  43718. this.forceProjectionMatrixCompute();
  43719. },
  43720. enumerable: true,
  43721. configurable: true
  43722. });
  43723. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43724. /**
  43725. * Allows scaling the angle of the light for shadow generation only.
  43726. */
  43727. get: function () {
  43728. return this._shadowAngleScale;
  43729. },
  43730. /**
  43731. * Allows scaling the angle of the light for shadow generation only.
  43732. */
  43733. set: function (value) {
  43734. this._shadowAngleScale = value;
  43735. this.forceProjectionMatrixCompute();
  43736. },
  43737. enumerable: true,
  43738. configurable: true
  43739. });
  43740. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  43741. /**
  43742. * Allows reading the projecton texture
  43743. */
  43744. get: function () {
  43745. return this._projectionTextureMatrix;
  43746. },
  43747. enumerable: true,
  43748. configurable: true
  43749. });
  43750. ;
  43751. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  43752. /**
  43753. * Gets the near clip of the Spotlight for texture projection.
  43754. */
  43755. get: function () {
  43756. return this._projectionTextureLightNear;
  43757. },
  43758. /**
  43759. * Sets the near clip of the Spotlight for texture projection.
  43760. */
  43761. set: function (value) {
  43762. this._projectionTextureLightNear = value;
  43763. this._projectionTextureProjectionLightDirty = true;
  43764. },
  43765. enumerable: true,
  43766. configurable: true
  43767. });
  43768. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  43769. /**
  43770. * Gets the far clip of the Spotlight for texture projection.
  43771. */
  43772. get: function () {
  43773. return this._projectionTextureLightFar;
  43774. },
  43775. /**
  43776. * Sets the far clip of the Spotlight for texture projection.
  43777. */
  43778. set: function (value) {
  43779. this._projectionTextureLightFar = value;
  43780. this._projectionTextureProjectionLightDirty = true;
  43781. },
  43782. enumerable: true,
  43783. configurable: true
  43784. });
  43785. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  43786. /**
  43787. * Gets the Up vector of the Spotlight for texture projection.
  43788. */
  43789. get: function () {
  43790. return this._projectionTextureUpDirection;
  43791. },
  43792. /**
  43793. * Sets the Up vector of the Spotlight for texture projection.
  43794. */
  43795. set: function (value) {
  43796. this._projectionTextureUpDirection = value;
  43797. this._projectionTextureProjectionLightDirty = true;
  43798. },
  43799. enumerable: true,
  43800. configurable: true
  43801. });
  43802. ;
  43803. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  43804. /**
  43805. * Gets the projection texture of the light.
  43806. */
  43807. get: function () {
  43808. return this._projectionTexture;
  43809. },
  43810. /**
  43811. * Sets the projection texture of the light.
  43812. */
  43813. set: function (value) {
  43814. this._projectionTexture = value;
  43815. this._projectionTextureDirty = true;
  43816. },
  43817. enumerable: true,
  43818. configurable: true
  43819. });
  43820. /**
  43821. * Returns the string "SpotLight".
  43822. * @returns the class name
  43823. */
  43824. SpotLight.prototype.getClassName = function () {
  43825. return "SpotLight";
  43826. };
  43827. /**
  43828. * Returns the integer 2.
  43829. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43830. */
  43831. SpotLight.prototype.getTypeID = function () {
  43832. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43833. };
  43834. /**
  43835. * Overrides the direction setter to recompute the projection texture view light Matrix.
  43836. */
  43837. SpotLight.prototype._setDirection = function (value) {
  43838. _super.prototype._setDirection.call(this, value);
  43839. this._projectionTextureViewLightDirty = true;
  43840. };
  43841. /**
  43842. * Overrides the position setter to recompute the projection texture view light Matrix.
  43843. */
  43844. SpotLight.prototype._setPosition = function (value) {
  43845. _super.prototype._setPosition.call(this, value);
  43846. this._projectionTextureViewLightDirty = true;
  43847. };
  43848. /**
  43849. * 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.
  43850. * Returns the SpotLight.
  43851. */
  43852. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43853. var activeCamera = this.getScene().activeCamera;
  43854. if (!activeCamera) {
  43855. return;
  43856. }
  43857. this._shadowAngleScale = this._shadowAngleScale || 1;
  43858. var angle = this._shadowAngleScale * this._angle;
  43859. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43860. };
  43861. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  43862. this._projectionTextureViewLightDirty = false;
  43863. this._projectionTextureDirty = true;
  43864. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  43865. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  43866. };
  43867. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  43868. this._projectionTextureProjectionLightDirty = false;
  43869. this._projectionTextureDirty = true;
  43870. var light_far = this.projectionTextureLightFar;
  43871. var light_near = this.projectionTextureLightNear;
  43872. var P = light_far / (light_far - light_near);
  43873. var Q = -P * light_near;
  43874. var S = 1.0 / Math.tan(this._angle / 2.0);
  43875. var A = 1.0;
  43876. 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);
  43877. };
  43878. /**
  43879. * Main function for light texture projection matrix computing.
  43880. */
  43881. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  43882. this._projectionTextureDirty = false;
  43883. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  43884. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  43885. };
  43886. SpotLight.prototype._buildUniformLayout = function () {
  43887. this._uniformBuffer.addUniform("vLightData", 4);
  43888. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43889. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43890. this._uniformBuffer.addUniform("vLightDirection", 3);
  43891. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43892. this._uniformBuffer.addUniform("depthValues", 2);
  43893. this._uniformBuffer.create();
  43894. };
  43895. /**
  43896. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43897. * @param effect The effect to update
  43898. * @param lightIndex The index of the light in the effect to update
  43899. * @returns The spot light
  43900. */
  43901. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43902. var normalizeDirection;
  43903. if (this.computeTransformedInformation()) {
  43904. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43905. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43906. }
  43907. else {
  43908. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43909. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43910. }
  43911. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43912. if (this.projectionTexture && this.projectionTexture.isReady()) {
  43913. if (this._projectionTextureViewLightDirty) {
  43914. this._computeProjectionTextureViewLightMatrix();
  43915. }
  43916. if (this._projectionTextureProjectionLightDirty) {
  43917. this._computeProjectionTextureProjectionLightMatrix();
  43918. }
  43919. if (this._projectionTextureDirty) {
  43920. this._computeProjectionTextureMatrix();
  43921. }
  43922. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  43923. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  43924. }
  43925. return this;
  43926. };
  43927. /**
  43928. * Disposes the light and the associated resources.
  43929. */
  43930. SpotLight.prototype.dispose = function () {
  43931. _super.prototype.dispose.call(this);
  43932. if (this._projectionTexture) {
  43933. this._projectionTexture.dispose();
  43934. }
  43935. };
  43936. __decorate([
  43937. BABYLON.serialize()
  43938. ], SpotLight.prototype, "angle", null);
  43939. __decorate([
  43940. BABYLON.serialize()
  43941. ], SpotLight.prototype, "shadowAngleScale", null);
  43942. __decorate([
  43943. BABYLON.serialize()
  43944. ], SpotLight.prototype, "exponent", void 0);
  43945. __decorate([
  43946. BABYLON.serialize()
  43947. ], SpotLight.prototype, "projectionTextureLightNear", null);
  43948. __decorate([
  43949. BABYLON.serialize()
  43950. ], SpotLight.prototype, "projectionTextureLightFar", null);
  43951. __decorate([
  43952. BABYLON.serialize()
  43953. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  43954. __decorate([
  43955. BABYLON.serializeAsTexture("projectedLightTexture")
  43956. ], SpotLight.prototype, "_projectionTexture", void 0);
  43957. return SpotLight;
  43958. }(BABYLON.ShadowLight));
  43959. BABYLON.SpotLight = SpotLight;
  43960. })(BABYLON || (BABYLON = {}));
  43961. //# sourceMappingURL=babylon.spotLight.js.map
  43962. var BABYLON;
  43963. (function (BABYLON) {
  43964. var AnimationRange = /** @class */ (function () {
  43965. function AnimationRange(name, from, to) {
  43966. this.name = name;
  43967. this.from = from;
  43968. this.to = to;
  43969. }
  43970. AnimationRange.prototype.clone = function () {
  43971. return new AnimationRange(this.name, this.from, this.to);
  43972. };
  43973. return AnimationRange;
  43974. }());
  43975. BABYLON.AnimationRange = AnimationRange;
  43976. /**
  43977. * Composed of a frame, and an action function
  43978. */
  43979. var AnimationEvent = /** @class */ (function () {
  43980. function AnimationEvent(frame, action, onlyOnce) {
  43981. this.frame = frame;
  43982. this.action = action;
  43983. this.onlyOnce = onlyOnce;
  43984. this.isDone = false;
  43985. }
  43986. return AnimationEvent;
  43987. }());
  43988. BABYLON.AnimationEvent = AnimationEvent;
  43989. var PathCursor = /** @class */ (function () {
  43990. function PathCursor(path) {
  43991. this.path = path;
  43992. this._onchange = new Array();
  43993. this.value = 0;
  43994. this.animations = new Array();
  43995. }
  43996. PathCursor.prototype.getPoint = function () {
  43997. var point = this.path.getPointAtLengthPosition(this.value);
  43998. return new BABYLON.Vector3(point.x, 0, point.y);
  43999. };
  44000. PathCursor.prototype.moveAhead = function (step) {
  44001. if (step === void 0) { step = 0.002; }
  44002. this.move(step);
  44003. return this;
  44004. };
  44005. PathCursor.prototype.moveBack = function (step) {
  44006. if (step === void 0) { step = 0.002; }
  44007. this.move(-step);
  44008. return this;
  44009. };
  44010. PathCursor.prototype.move = function (step) {
  44011. if (Math.abs(step) > 1) {
  44012. throw "step size should be less than 1.";
  44013. }
  44014. this.value += step;
  44015. this.ensureLimits();
  44016. this.raiseOnChange();
  44017. return this;
  44018. };
  44019. PathCursor.prototype.ensureLimits = function () {
  44020. while (this.value > 1) {
  44021. this.value -= 1;
  44022. }
  44023. while (this.value < 0) {
  44024. this.value += 1;
  44025. }
  44026. return this;
  44027. };
  44028. // used by animation engine
  44029. PathCursor.prototype.raiseOnChange = function () {
  44030. var _this = this;
  44031. this._onchange.forEach(function (f) { return f(_this); });
  44032. return this;
  44033. };
  44034. PathCursor.prototype.onchange = function (f) {
  44035. this._onchange.push(f);
  44036. return this;
  44037. };
  44038. return PathCursor;
  44039. }());
  44040. BABYLON.PathCursor = PathCursor;
  44041. var AnimationKeyInterpolation;
  44042. (function (AnimationKeyInterpolation) {
  44043. /**
  44044. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  44045. */
  44046. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  44047. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  44048. var Animation = /** @class */ (function () {
  44049. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  44050. this.name = name;
  44051. this.targetProperty = targetProperty;
  44052. this.framePerSecond = framePerSecond;
  44053. this.dataType = dataType;
  44054. this.loopMode = loopMode;
  44055. this.enableBlending = enableBlending;
  44056. this._runtimeAnimations = new Array();
  44057. // The set of event that will be linked to this animation
  44058. this._events = new Array();
  44059. this.blendingSpeed = 0.01;
  44060. this._ranges = {};
  44061. this.targetPropertyPath = targetProperty.split(".");
  44062. this.dataType = dataType;
  44063. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  44064. }
  44065. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  44066. var dataType = undefined;
  44067. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  44068. dataType = Animation.ANIMATIONTYPE_FLOAT;
  44069. }
  44070. else if (from instanceof BABYLON.Quaternion) {
  44071. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  44072. }
  44073. else if (from instanceof BABYLON.Vector3) {
  44074. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  44075. }
  44076. else if (from instanceof BABYLON.Vector2) {
  44077. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  44078. }
  44079. else if (from instanceof BABYLON.Color3) {
  44080. dataType = Animation.ANIMATIONTYPE_COLOR3;
  44081. }
  44082. else if (from instanceof BABYLON.Size) {
  44083. dataType = Animation.ANIMATIONTYPE_SIZE;
  44084. }
  44085. if (dataType == undefined) {
  44086. return null;
  44087. }
  44088. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  44089. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  44090. animation.setKeys(keys);
  44091. if (easingFunction !== undefined) {
  44092. animation.setEasingFunction(easingFunction);
  44093. }
  44094. return animation;
  44095. };
  44096. /**
  44097. * Sets up an animation.
  44098. * @param property the property to animate
  44099. * @param animationType the animation type to apply
  44100. * @param easingFunction the easing function used in the animation
  44101. * @returns The created animation
  44102. */
  44103. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  44104. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  44105. animation.setEasingFunction(easingFunction);
  44106. return animation;
  44107. };
  44108. /**
  44109. * Create and start an animation on a node
  44110. * @param {string} name defines the name of the global animation that will be run on all nodes
  44111. * @param {BABYLON.Node} node defines the root node where the animation will take place
  44112. * @param {string} targetProperty defines property to animate
  44113. * @param {number} framePerSecond defines the number of frame per second yo use
  44114. * @param {number} totalFrame defines the number of frames in total
  44115. * @param {any} from defines the initial value
  44116. * @param {any} to defines the final value
  44117. * @param {number} loopMode defines which loop mode you want to use (off by default)
  44118. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  44119. * @param onAnimationEnd defines the callback to call when animation end
  44120. * @returns the animatable created for this animation
  44121. */
  44122. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44123. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44124. if (!animation) {
  44125. return null;
  44126. }
  44127. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44128. };
  44129. /**
  44130. * Create and start an animation on a node and its descendants
  44131. * @param {string} name defines the name of the global animation that will be run on all nodes
  44132. * @param {BABYLON.Node} node defines the root node where the animation will take place
  44133. * @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.
  44134. * @param {string} targetProperty defines property to animate
  44135. * @param {number} framePerSecond defines the number of frame per second yo use
  44136. * @param {number} totalFrame defines the number of frames in total
  44137. * @param {any} from defines the initial value
  44138. * @param {any} to defines the final value
  44139. * @param {number} loopMode defines which loop mode you want to use (off by default)
  44140. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  44141. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  44142. * @returns the list of animatables created for all nodes
  44143. * @example https://www.babylonjs-playground.com/#MH0VLI
  44144. */
  44145. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44146. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44147. if (!animation) {
  44148. return null;
  44149. }
  44150. var scene = node.getScene();
  44151. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44152. };
  44153. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44154. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44155. if (!animation) {
  44156. return null;
  44157. }
  44158. node.animations.push(animation);
  44159. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44160. };
  44161. /**
  44162. * Transition property of the Camera to the target Value.
  44163. * @param property The property to transition
  44164. * @param targetValue The target Value of the property
  44165. * @param host The object where the property to animate belongs
  44166. * @param scene Scene used to run the animation
  44167. * @param frameRate Framerate (in frame/s) to use
  44168. * @param transition The transition type we want to use
  44169. * @param duration The duration of the animation, in milliseconds
  44170. * @param onAnimationEnd Call back trigger at the end of the animation.
  44171. */
  44172. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  44173. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  44174. if (duration <= 0) {
  44175. host[property] = targetValue;
  44176. if (onAnimationEnd) {
  44177. onAnimationEnd();
  44178. }
  44179. return null;
  44180. }
  44181. var endFrame = frameRate * (duration / 1000);
  44182. transition.setKeys([{
  44183. frame: 0,
  44184. value: host[property].clone ? host[property].clone() : host[property]
  44185. },
  44186. {
  44187. frame: endFrame,
  44188. value: targetValue
  44189. }]);
  44190. if (!host.animations) {
  44191. host.animations = [];
  44192. }
  44193. host.animations.push(transition);
  44194. var animation = scene.beginAnimation(host, 0, endFrame, false);
  44195. animation.onAnimationEnd = onAnimationEnd;
  44196. return animation;
  44197. };
  44198. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  44199. /**
  44200. * Return the array of runtime animations currently using this animation
  44201. */
  44202. get: function () {
  44203. return this._runtimeAnimations;
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  44209. get: function () {
  44210. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  44211. var runtimeAnimation = _a[_i];
  44212. if (!runtimeAnimation.isStopped) {
  44213. return true;
  44214. }
  44215. }
  44216. return false;
  44217. },
  44218. enumerable: true,
  44219. configurable: true
  44220. });
  44221. // Methods
  44222. /**
  44223. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  44224. */
  44225. Animation.prototype.toString = function (fullDetails) {
  44226. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  44227. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  44228. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  44229. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  44230. if (fullDetails) {
  44231. ret += ", Ranges: {";
  44232. var first = true;
  44233. for (var name in this._ranges) {
  44234. if (first) {
  44235. ret += ", ";
  44236. first = false;
  44237. }
  44238. ret += name;
  44239. }
  44240. ret += "}";
  44241. }
  44242. return ret;
  44243. };
  44244. /**
  44245. * Add an event to this animation.
  44246. */
  44247. Animation.prototype.addEvent = function (event) {
  44248. this._events.push(event);
  44249. };
  44250. /**
  44251. * Remove all events found at the given frame
  44252. * @param frame
  44253. */
  44254. Animation.prototype.removeEvents = function (frame) {
  44255. for (var index = 0; index < this._events.length; index++) {
  44256. if (this._events[index].frame === frame) {
  44257. this._events.splice(index, 1);
  44258. index--;
  44259. }
  44260. }
  44261. };
  44262. Animation.prototype.getEvents = function () {
  44263. return this._events;
  44264. };
  44265. Animation.prototype.createRange = function (name, from, to) {
  44266. // check name not already in use; could happen for bones after serialized
  44267. if (!this._ranges[name]) {
  44268. this._ranges[name] = new AnimationRange(name, from, to);
  44269. }
  44270. };
  44271. Animation.prototype.deleteRange = function (name, deleteFrames) {
  44272. if (deleteFrames === void 0) { deleteFrames = true; }
  44273. var range = this._ranges[name];
  44274. if (!range) {
  44275. return;
  44276. }
  44277. if (deleteFrames) {
  44278. var from = range.from;
  44279. var to = range.to;
  44280. // this loop MUST go high to low for multiple splices to work
  44281. for (var key = this._keys.length - 1; key >= 0; key--) {
  44282. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  44283. this._keys.splice(key, 1);
  44284. }
  44285. }
  44286. }
  44287. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  44288. };
  44289. Animation.prototype.getRange = function (name) {
  44290. return this._ranges[name];
  44291. };
  44292. Animation.prototype.getKeys = function () {
  44293. return this._keys;
  44294. };
  44295. Animation.prototype.getHighestFrame = function () {
  44296. var ret = 0;
  44297. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  44298. if (ret < this._keys[key].frame) {
  44299. ret = this._keys[key].frame;
  44300. }
  44301. }
  44302. return ret;
  44303. };
  44304. Animation.prototype.getEasingFunction = function () {
  44305. return this._easingFunction;
  44306. };
  44307. Animation.prototype.setEasingFunction = function (easingFunction) {
  44308. this._easingFunction = easingFunction;
  44309. };
  44310. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  44311. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  44312. };
  44313. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44314. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44315. };
  44316. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  44317. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  44318. };
  44319. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44320. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  44321. };
  44322. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  44323. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  44324. };
  44325. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44326. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44327. };
  44328. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  44329. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  44330. };
  44331. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44332. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44333. };
  44334. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  44335. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  44336. };
  44337. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  44338. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  44339. };
  44340. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  44341. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  44342. };
  44343. Animation.prototype.clone = function () {
  44344. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  44345. clone.enableBlending = this.enableBlending;
  44346. clone.blendingSpeed = this.blendingSpeed;
  44347. if (this._keys) {
  44348. clone.setKeys(this._keys);
  44349. }
  44350. if (this._ranges) {
  44351. clone._ranges = {};
  44352. for (var name in this._ranges) {
  44353. var range = this._ranges[name];
  44354. if (!range) {
  44355. continue;
  44356. }
  44357. clone._ranges[name] = range.clone();
  44358. }
  44359. }
  44360. return clone;
  44361. };
  44362. Animation.prototype.setKeys = function (values) {
  44363. this._keys = values.slice(0);
  44364. };
  44365. Animation.prototype.serialize = function () {
  44366. var serializationObject = {};
  44367. serializationObject.name = this.name;
  44368. serializationObject.property = this.targetProperty;
  44369. serializationObject.framePerSecond = this.framePerSecond;
  44370. serializationObject.dataType = this.dataType;
  44371. serializationObject.loopBehavior = this.loopMode;
  44372. serializationObject.enableBlending = this.enableBlending;
  44373. serializationObject.blendingSpeed = this.blendingSpeed;
  44374. var dataType = this.dataType;
  44375. serializationObject.keys = [];
  44376. var keys = this.getKeys();
  44377. for (var index = 0; index < keys.length; index++) {
  44378. var animationKey = keys[index];
  44379. var key = {};
  44380. key.frame = animationKey.frame;
  44381. switch (dataType) {
  44382. case Animation.ANIMATIONTYPE_FLOAT:
  44383. key.values = [animationKey.value];
  44384. break;
  44385. case Animation.ANIMATIONTYPE_QUATERNION:
  44386. case Animation.ANIMATIONTYPE_MATRIX:
  44387. case Animation.ANIMATIONTYPE_VECTOR3:
  44388. case Animation.ANIMATIONTYPE_COLOR3:
  44389. key.values = animationKey.value.asArray();
  44390. break;
  44391. }
  44392. serializationObject.keys.push(key);
  44393. }
  44394. serializationObject.ranges = [];
  44395. for (var name in this._ranges) {
  44396. var source = this._ranges[name];
  44397. if (!source) {
  44398. continue;
  44399. }
  44400. var range = {};
  44401. range.name = name;
  44402. range.from = source.from;
  44403. range.to = source.to;
  44404. serializationObject.ranges.push(range);
  44405. }
  44406. return serializationObject;
  44407. };
  44408. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  44409. get: function () {
  44410. return Animation._ANIMATIONTYPE_FLOAT;
  44411. },
  44412. enumerable: true,
  44413. configurable: true
  44414. });
  44415. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  44416. get: function () {
  44417. return Animation._ANIMATIONTYPE_VECTOR3;
  44418. },
  44419. enumerable: true,
  44420. configurable: true
  44421. });
  44422. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  44423. get: function () {
  44424. return Animation._ANIMATIONTYPE_VECTOR2;
  44425. },
  44426. enumerable: true,
  44427. configurable: true
  44428. });
  44429. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  44430. get: function () {
  44431. return Animation._ANIMATIONTYPE_SIZE;
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  44437. get: function () {
  44438. return Animation._ANIMATIONTYPE_QUATERNION;
  44439. },
  44440. enumerable: true,
  44441. configurable: true
  44442. });
  44443. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  44444. get: function () {
  44445. return Animation._ANIMATIONTYPE_MATRIX;
  44446. },
  44447. enumerable: true,
  44448. configurable: true
  44449. });
  44450. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  44451. get: function () {
  44452. return Animation._ANIMATIONTYPE_COLOR3;
  44453. },
  44454. enumerable: true,
  44455. configurable: true
  44456. });
  44457. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  44458. get: function () {
  44459. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  44460. },
  44461. enumerable: true,
  44462. configurable: true
  44463. });
  44464. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  44465. get: function () {
  44466. return Animation._ANIMATIONLOOPMODE_CYCLE;
  44467. },
  44468. enumerable: true,
  44469. configurable: true
  44470. });
  44471. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  44472. get: function () {
  44473. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  44474. },
  44475. enumerable: true,
  44476. configurable: true
  44477. });
  44478. Animation.Parse = function (parsedAnimation) {
  44479. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  44480. var dataType = parsedAnimation.dataType;
  44481. var keys = [];
  44482. var data;
  44483. var index;
  44484. if (parsedAnimation.enableBlending) {
  44485. animation.enableBlending = parsedAnimation.enableBlending;
  44486. }
  44487. if (parsedAnimation.blendingSpeed) {
  44488. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  44489. }
  44490. for (index = 0; index < parsedAnimation.keys.length; index++) {
  44491. var key = parsedAnimation.keys[index];
  44492. var inTangent;
  44493. var outTangent;
  44494. switch (dataType) {
  44495. case Animation.ANIMATIONTYPE_FLOAT:
  44496. data = key.values[0];
  44497. if (key.values.length >= 1) {
  44498. inTangent = key.values[1];
  44499. }
  44500. if (key.values.length >= 2) {
  44501. outTangent = key.values[2];
  44502. }
  44503. break;
  44504. case Animation.ANIMATIONTYPE_QUATERNION:
  44505. data = BABYLON.Quaternion.FromArray(key.values);
  44506. if (key.values.length >= 8) {
  44507. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  44508. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  44509. inTangent = _inTangent;
  44510. }
  44511. }
  44512. if (key.values.length >= 12) {
  44513. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  44514. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  44515. outTangent = _outTangent;
  44516. }
  44517. }
  44518. break;
  44519. case Animation.ANIMATIONTYPE_MATRIX:
  44520. data = BABYLON.Matrix.FromArray(key.values);
  44521. break;
  44522. case Animation.ANIMATIONTYPE_COLOR3:
  44523. data = BABYLON.Color3.FromArray(key.values);
  44524. break;
  44525. case Animation.ANIMATIONTYPE_VECTOR3:
  44526. default:
  44527. data = BABYLON.Vector3.FromArray(key.values);
  44528. break;
  44529. }
  44530. var keyData = {};
  44531. keyData.frame = key.frame;
  44532. keyData.value = data;
  44533. if (inTangent != undefined) {
  44534. keyData.inTangent = inTangent;
  44535. }
  44536. if (outTangent != undefined) {
  44537. keyData.outTangent = outTangent;
  44538. }
  44539. keys.push(keyData);
  44540. }
  44541. animation.setKeys(keys);
  44542. if (parsedAnimation.ranges) {
  44543. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  44544. data = parsedAnimation.ranges[index];
  44545. animation.createRange(data.name, data.from, data.to);
  44546. }
  44547. }
  44548. return animation;
  44549. };
  44550. Animation.AppendSerializedAnimations = function (source, destination) {
  44551. if (source.animations) {
  44552. destination.animations = [];
  44553. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  44554. var animation = source.animations[animationIndex];
  44555. destination.animations.push(animation.serialize());
  44556. }
  44557. }
  44558. };
  44559. Animation.AllowMatricesInterpolation = false;
  44560. // Statics
  44561. Animation._ANIMATIONTYPE_FLOAT = 0;
  44562. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  44563. Animation._ANIMATIONTYPE_QUATERNION = 2;
  44564. Animation._ANIMATIONTYPE_MATRIX = 3;
  44565. Animation._ANIMATIONTYPE_COLOR3 = 4;
  44566. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  44567. Animation._ANIMATIONTYPE_SIZE = 6;
  44568. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  44569. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  44570. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  44571. return Animation;
  44572. }());
  44573. BABYLON.Animation = Animation;
  44574. })(BABYLON || (BABYLON = {}));
  44575. //# sourceMappingURL=babylon.animation.js.map
  44576. var BABYLON;
  44577. (function (BABYLON) {
  44578. /**
  44579. * This class defines the direct association between an animation and a target
  44580. */
  44581. var TargetedAnimation = /** @class */ (function () {
  44582. function TargetedAnimation() {
  44583. }
  44584. return TargetedAnimation;
  44585. }());
  44586. BABYLON.TargetedAnimation = TargetedAnimation;
  44587. /**
  44588. * Use this class to create coordinated animations on multiple targets
  44589. */
  44590. var AnimationGroup = /** @class */ (function () {
  44591. function AnimationGroup(name, scene) {
  44592. if (scene === void 0) { scene = null; }
  44593. this.name = name;
  44594. this._targetedAnimations = new Array();
  44595. this._animatables = new Array();
  44596. this._from = Number.MAX_VALUE;
  44597. this._to = -Number.MAX_VALUE;
  44598. this._speedRatio = 1;
  44599. this.onAnimationEndObservable = new BABYLON.Observable();
  44600. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44601. this._scene.animationGroups.push(this);
  44602. }
  44603. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  44604. /**
  44605. * Define if the animations are started
  44606. */
  44607. get: function () {
  44608. return this._isStarted;
  44609. },
  44610. enumerable: true,
  44611. configurable: true
  44612. });
  44613. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  44614. /**
  44615. * Gets or sets the speed ratio to use for all animations
  44616. */
  44617. get: function () {
  44618. return this._speedRatio;
  44619. },
  44620. /**
  44621. * Gets or sets the speed ratio to use for all animations
  44622. */
  44623. set: function (value) {
  44624. if (this._speedRatio === value) {
  44625. return;
  44626. }
  44627. this._speedRatio = value;
  44628. for (var index = 0; index < this._animatables.length; index++) {
  44629. var animatable = this._animatables[index];
  44630. animatable.speedRatio = this._speedRatio;
  44631. }
  44632. },
  44633. enumerable: true,
  44634. configurable: true
  44635. });
  44636. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  44637. /**
  44638. * Gets the targeted animations for this animation group
  44639. */
  44640. get: function () {
  44641. return this._targetedAnimations;
  44642. },
  44643. enumerable: true,
  44644. configurable: true
  44645. });
  44646. /**
  44647. * Add an animation (with its target) in the group
  44648. * @param animation defines the animation we want to add
  44649. * @param target defines the target of the animation
  44650. * @returns the {BABYLON.TargetedAnimation} object
  44651. */
  44652. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  44653. var targetedAnimation = {
  44654. animation: animation,
  44655. target: target
  44656. };
  44657. var keys = animation.getKeys();
  44658. if (this._from > keys[0].frame) {
  44659. this._from = keys[0].frame;
  44660. }
  44661. if (this._to < keys[keys.length - 1].frame) {
  44662. this._to = keys[keys.length - 1].frame;
  44663. }
  44664. this._targetedAnimations.push(targetedAnimation);
  44665. return targetedAnimation;
  44666. };
  44667. /**
  44668. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  44669. * It can add constant keys at begin or end
  44670. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  44671. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  44672. */
  44673. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  44674. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  44675. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  44676. beginFrame = Math.max(beginFrame, this._from);
  44677. endFrame = Math.min(endFrame, this._to);
  44678. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44679. var targetedAnimation = this._targetedAnimations[index];
  44680. var keys = targetedAnimation.animation.getKeys();
  44681. var startKey = keys[0];
  44682. var endKey = keys[keys.length - 1];
  44683. if (startKey.frame > beginFrame) {
  44684. var newKey = {
  44685. frame: beginFrame,
  44686. value: startKey.value,
  44687. inTangent: startKey.inTangent,
  44688. outTangent: startKey.outTangent,
  44689. interpolation: startKey.interpolation
  44690. };
  44691. keys.splice(0, 0, newKey);
  44692. }
  44693. if (endKey.frame < endFrame) {
  44694. var newKey = {
  44695. frame: endFrame,
  44696. value: endKey.value,
  44697. inTangent: endKey.outTangent,
  44698. outTangent: endKey.outTangent,
  44699. interpolation: endKey.interpolation
  44700. };
  44701. keys.push(newKey);
  44702. }
  44703. }
  44704. return this;
  44705. };
  44706. /**
  44707. * Start all animations on given targets
  44708. * @param loop defines if animations must loop
  44709. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  44710. */
  44711. AnimationGroup.prototype.start = function (loop, speedRatio) {
  44712. var _this = this;
  44713. if (loop === void 0) { loop = false; }
  44714. if (speedRatio === void 0) { speedRatio = 1; }
  44715. if (this._isStarted || this._targetedAnimations.length === 0) {
  44716. return this;
  44717. }
  44718. var _loop_1 = function () {
  44719. var targetedAnimation = this_1._targetedAnimations[index];
  44720. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  44721. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  44722. }));
  44723. };
  44724. var this_1 = this;
  44725. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44726. _loop_1();
  44727. }
  44728. this._speedRatio = speedRatio;
  44729. this._isStarted = true;
  44730. return this;
  44731. };
  44732. /**
  44733. * Pause all animations
  44734. */
  44735. AnimationGroup.prototype.pause = function () {
  44736. if (!this._isStarted) {
  44737. return this;
  44738. }
  44739. for (var index = 0; index < this._animatables.length; index++) {
  44740. var animatable = this._animatables[index];
  44741. animatable.pause();
  44742. }
  44743. return this;
  44744. };
  44745. /**
  44746. * Play all animations to initial state
  44747. * This function will start() the animations if they were not started or will restart() them if they were paused
  44748. * @param loop defines if animations must loop
  44749. */
  44750. AnimationGroup.prototype.play = function (loop) {
  44751. if (this.isStarted) {
  44752. if (loop !== undefined) {
  44753. for (var index = 0; index < this._animatables.length; index++) {
  44754. var animatable = this._animatables[index];
  44755. animatable.loopAnimation = loop;
  44756. }
  44757. }
  44758. this.restart();
  44759. }
  44760. else {
  44761. this.start(loop, this._speedRatio);
  44762. }
  44763. return this;
  44764. };
  44765. /**
  44766. * Reset all animations to initial state
  44767. */
  44768. AnimationGroup.prototype.reset = function () {
  44769. if (!this._isStarted) {
  44770. return this;
  44771. }
  44772. for (var index = 0; index < this._animatables.length; index++) {
  44773. var animatable = this._animatables[index];
  44774. animatable.reset();
  44775. }
  44776. return this;
  44777. };
  44778. /**
  44779. * Restart animations from key 0
  44780. */
  44781. AnimationGroup.prototype.restart = function () {
  44782. if (!this._isStarted) {
  44783. return this;
  44784. }
  44785. for (var index = 0; index < this._animatables.length; index++) {
  44786. var animatable = this._animatables[index];
  44787. animatable.restart();
  44788. }
  44789. return this;
  44790. };
  44791. /**
  44792. * Stop all animations
  44793. */
  44794. AnimationGroup.prototype.stop = function () {
  44795. if (!this._isStarted) {
  44796. return this;
  44797. }
  44798. for (var index = 0; index < this._animatables.length; index++) {
  44799. var animatable = this._animatables[index];
  44800. animatable.stop();
  44801. }
  44802. this._isStarted = false;
  44803. return this;
  44804. };
  44805. /**
  44806. * Dispose all associated resources
  44807. */
  44808. AnimationGroup.prototype.dispose = function () {
  44809. this._targetedAnimations = [];
  44810. this._animatables = [];
  44811. var index = this._scene.animationGroups.indexOf(this);
  44812. if (index > -1) {
  44813. this._scene.animationGroups.splice(index, 1);
  44814. }
  44815. };
  44816. return AnimationGroup;
  44817. }());
  44818. BABYLON.AnimationGroup = AnimationGroup;
  44819. })(BABYLON || (BABYLON = {}));
  44820. //# sourceMappingURL=babylon.animationGroup.js.map
  44821. var BABYLON;
  44822. (function (BABYLON) {
  44823. var RuntimeAnimation = /** @class */ (function () {
  44824. function RuntimeAnimation(target, animation) {
  44825. this._offsetsCache = {};
  44826. this._highLimitsCache = {};
  44827. this._stopped = false;
  44828. this._blendingFactor = 0;
  44829. this._ratioOffset = 0;
  44830. this._animation = animation;
  44831. this._target = target;
  44832. animation._runtimeAnimations.push(this);
  44833. }
  44834. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44835. get: function () {
  44836. return this._animation;
  44837. },
  44838. enumerable: true,
  44839. configurable: true
  44840. });
  44841. RuntimeAnimation.prototype.reset = function () {
  44842. this._offsetsCache = {};
  44843. this._highLimitsCache = {};
  44844. this.currentFrame = 0;
  44845. this._blendingFactor = 0;
  44846. this._originalBlendValue = null;
  44847. };
  44848. RuntimeAnimation.prototype.isStopped = function () {
  44849. return this._stopped;
  44850. };
  44851. RuntimeAnimation.prototype.dispose = function () {
  44852. var index = this._animation.runtimeAnimations.indexOf(this);
  44853. if (index > -1) {
  44854. this._animation.runtimeAnimations.splice(index, 1);
  44855. }
  44856. };
  44857. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44858. if (typeof value === "function") {
  44859. return value();
  44860. }
  44861. return value;
  44862. };
  44863. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44864. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44865. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44866. }
  44867. this.currentFrame = currentFrame;
  44868. var keys = this._animation.getKeys();
  44869. // Try to get a hash to find the right key
  44870. 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));
  44871. if (keys[startKeyIndex].frame >= currentFrame) {
  44872. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44873. startKeyIndex--;
  44874. }
  44875. }
  44876. for (var key = startKeyIndex; key < keys.length; key++) {
  44877. var endKey = keys[key + 1];
  44878. if (endKey.frame >= currentFrame) {
  44879. var startKey = keys[key];
  44880. var startValue = this._getKeyValue(startKey.value);
  44881. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44882. return startValue;
  44883. }
  44884. var endValue = this._getKeyValue(endKey.value);
  44885. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44886. var frameDelta = endKey.frame - startKey.frame;
  44887. // gradient : percent of currentFrame between the frame inf and the frame sup
  44888. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44889. // check for easingFunction and correction of gradient
  44890. var easingFunction = this._animation.getEasingFunction();
  44891. if (easingFunction != null) {
  44892. gradient = easingFunction.ease(gradient);
  44893. }
  44894. switch (this._animation.dataType) {
  44895. // Float
  44896. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44897. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44898. switch (loopMode) {
  44899. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44900. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44901. return floatValue;
  44902. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44903. return offsetValue * repeatCount + floatValue;
  44904. }
  44905. break;
  44906. // Quaternion
  44907. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44908. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44909. switch (loopMode) {
  44910. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44911. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44912. return quatValue;
  44913. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44914. return quatValue.add(offsetValue.scale(repeatCount));
  44915. }
  44916. return quatValue;
  44917. // Vector3
  44918. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44919. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44920. switch (loopMode) {
  44921. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44922. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44923. return vec3Value;
  44924. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44925. return vec3Value.add(offsetValue.scale(repeatCount));
  44926. }
  44927. // Vector2
  44928. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44929. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44930. switch (loopMode) {
  44931. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44932. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44933. return vec2Value;
  44934. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44935. return vec2Value.add(offsetValue.scale(repeatCount));
  44936. }
  44937. // Size
  44938. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44939. switch (loopMode) {
  44940. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44941. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44942. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44943. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44944. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44945. }
  44946. // Color3
  44947. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44948. switch (loopMode) {
  44949. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44950. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44951. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44952. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44953. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44954. }
  44955. // Matrix
  44956. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44957. switch (loopMode) {
  44958. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44959. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44960. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44961. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44962. }
  44963. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44964. return startValue;
  44965. }
  44966. default:
  44967. break;
  44968. }
  44969. break;
  44970. }
  44971. }
  44972. return this._getKeyValue(keys[keys.length - 1].value);
  44973. };
  44974. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44975. if (blend === void 0) { blend = false; }
  44976. // Set value
  44977. var path;
  44978. var destination;
  44979. var targetPropertyPath = this._animation.targetPropertyPath;
  44980. if (targetPropertyPath.length > 1) {
  44981. var property = this._target[targetPropertyPath[0]];
  44982. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44983. property = property[targetPropertyPath[index]];
  44984. }
  44985. path = targetPropertyPath[targetPropertyPath.length - 1];
  44986. destination = property;
  44987. }
  44988. else {
  44989. path = targetPropertyPath[0];
  44990. destination = this._target;
  44991. }
  44992. // Blending
  44993. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44994. if (!this._originalBlendValue) {
  44995. if (destination[path].clone) {
  44996. this._originalBlendValue = destination[path].clone();
  44997. }
  44998. else {
  44999. this._originalBlendValue = destination[path];
  45000. }
  45001. }
  45002. if (this._originalBlendValue.prototype) {
  45003. if (this._originalBlendValue.prototype.Lerp) {
  45004. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  45005. }
  45006. else {
  45007. destination[path] = currentValue;
  45008. }
  45009. }
  45010. else if (this._originalBlendValue.m) {
  45011. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  45012. }
  45013. else {
  45014. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  45015. }
  45016. this._blendingFactor += this._animation.blendingSpeed;
  45017. }
  45018. else {
  45019. destination[path] = currentValue;
  45020. }
  45021. if (this._target.markAsDirty) {
  45022. this._target.markAsDirty(this._animation.targetProperty);
  45023. }
  45024. };
  45025. RuntimeAnimation.prototype.goToFrame = function (frame) {
  45026. var keys = this._animation.getKeys();
  45027. if (frame < keys[0].frame) {
  45028. frame = keys[0].frame;
  45029. }
  45030. else if (frame > keys[keys.length - 1].frame) {
  45031. frame = keys[keys.length - 1].frame;
  45032. }
  45033. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  45034. this.setValue(currentValue);
  45035. };
  45036. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  45037. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  45038. this._ratioOffset = this._previousRatio - newRatio;
  45039. };
  45040. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  45041. if (blend === void 0) { blend = false; }
  45042. var targetPropertyPath = this._animation.targetPropertyPath;
  45043. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  45044. this._stopped = true;
  45045. return false;
  45046. }
  45047. var returnValue = true;
  45048. var keys = this._animation.getKeys();
  45049. // Adding a start key at frame 0 if missing
  45050. if (keys[0].frame !== 0) {
  45051. var newKey = { frame: 0, value: keys[0].value };
  45052. keys.splice(0, 0, newKey);
  45053. }
  45054. // Check limits
  45055. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  45056. from = keys[0].frame;
  45057. }
  45058. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  45059. to = keys[keys.length - 1].frame;
  45060. }
  45061. //to and from cannot be the same key
  45062. if (from === to) {
  45063. if (from > keys[0].frame) {
  45064. from--;
  45065. }
  45066. else if (to < keys[keys.length - 1].frame) {
  45067. to++;
  45068. }
  45069. }
  45070. // Compute ratio
  45071. var range = to - from;
  45072. var offsetValue;
  45073. // ratio represents the frame delta between from and to
  45074. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  45075. var highLimitValue = 0;
  45076. this._previousDelay = delay;
  45077. this._previousRatio = ratio;
  45078. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  45079. returnValue = false;
  45080. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  45081. }
  45082. else {
  45083. // Get max value if required
  45084. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  45085. var keyOffset = to.toString() + from.toString();
  45086. if (!this._offsetsCache[keyOffset]) {
  45087. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  45088. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  45089. switch (this._animation.dataType) {
  45090. // Float
  45091. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  45092. this._offsetsCache[keyOffset] = toValue - fromValue;
  45093. break;
  45094. // Quaternion
  45095. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  45096. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45097. break;
  45098. // Vector3
  45099. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  45100. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45101. // Vector2
  45102. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  45103. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45104. // Size
  45105. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  45106. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45107. // Color3
  45108. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  45109. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45110. default:
  45111. break;
  45112. }
  45113. this._highLimitsCache[keyOffset] = toValue;
  45114. }
  45115. highLimitValue = this._highLimitsCache[keyOffset];
  45116. offsetValue = this._offsetsCache[keyOffset];
  45117. }
  45118. }
  45119. if (offsetValue === undefined) {
  45120. switch (this._animation.dataType) {
  45121. // Float
  45122. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  45123. offsetValue = 0;
  45124. break;
  45125. // Quaternion
  45126. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  45127. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  45128. break;
  45129. // Vector3
  45130. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  45131. offsetValue = BABYLON.Vector3.Zero();
  45132. break;
  45133. // Vector2
  45134. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  45135. offsetValue = BABYLON.Vector2.Zero();
  45136. break;
  45137. // Size
  45138. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  45139. offsetValue = BABYLON.Size.Zero();
  45140. break;
  45141. // Color3
  45142. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  45143. offsetValue = BABYLON.Color3.Black();
  45144. }
  45145. }
  45146. // Compute value
  45147. var repeatCount = (ratio / range) >> 0;
  45148. var currentFrame = returnValue ? from + ratio % range : to;
  45149. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  45150. // Set value
  45151. this.setValue(currentValue);
  45152. // Check events
  45153. var events = this._animation.getEvents();
  45154. for (var index = 0; index < events.length; index++) {
  45155. // Make sure current frame has passed event frame and that event frame is within the current range
  45156. // Also, handle both forward and reverse animations
  45157. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  45158. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  45159. var event = events[index];
  45160. if (!event.isDone) {
  45161. // If event should be done only once, remove it.
  45162. if (event.onlyOnce) {
  45163. events.splice(index, 1);
  45164. index--;
  45165. }
  45166. event.isDone = true;
  45167. event.action();
  45168. } // Don't do anything if the event has already be done.
  45169. }
  45170. else if (events[index].isDone && !events[index].onlyOnce) {
  45171. // reset event, the animation is looping
  45172. events[index].isDone = false;
  45173. }
  45174. }
  45175. if (!returnValue) {
  45176. this._stopped = true;
  45177. }
  45178. return returnValue;
  45179. };
  45180. return RuntimeAnimation;
  45181. }());
  45182. BABYLON.RuntimeAnimation = RuntimeAnimation;
  45183. })(BABYLON || (BABYLON = {}));
  45184. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  45185. var BABYLON;
  45186. (function (BABYLON) {
  45187. var Animatable = /** @class */ (function () {
  45188. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  45189. if (fromFrame === void 0) { fromFrame = 0; }
  45190. if (toFrame === void 0) { toFrame = 100; }
  45191. if (loopAnimation === void 0) { loopAnimation = false; }
  45192. if (speedRatio === void 0) { speedRatio = 1.0; }
  45193. this.target = target;
  45194. this.fromFrame = fromFrame;
  45195. this.toFrame = toFrame;
  45196. this.loopAnimation = loopAnimation;
  45197. this.onAnimationEnd = onAnimationEnd;
  45198. this._localDelayOffset = null;
  45199. this._pausedDelay = null;
  45200. this._runtimeAnimations = new Array();
  45201. this._paused = false;
  45202. this._speedRatio = 1;
  45203. this.animationStarted = false;
  45204. if (animations) {
  45205. this.appendAnimations(target, animations);
  45206. }
  45207. this._speedRatio = speedRatio;
  45208. this._scene = scene;
  45209. scene._activeAnimatables.push(this);
  45210. }
  45211. Object.defineProperty(Animatable.prototype, "speedRatio", {
  45212. get: function () {
  45213. return this._speedRatio;
  45214. },
  45215. set: function (value) {
  45216. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  45217. var animation = this._runtimeAnimations[index];
  45218. animation._prepareForSpeedRatioChange(value);
  45219. }
  45220. this._speedRatio = value;
  45221. },
  45222. enumerable: true,
  45223. configurable: true
  45224. });
  45225. // Methods
  45226. Animatable.prototype.getAnimations = function () {
  45227. return this._runtimeAnimations;
  45228. };
  45229. Animatable.prototype.appendAnimations = function (target, animations) {
  45230. for (var index = 0; index < animations.length; index++) {
  45231. var animation = animations[index];
  45232. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  45233. }
  45234. };
  45235. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  45236. var runtimeAnimations = this._runtimeAnimations;
  45237. for (var index = 0; index < runtimeAnimations.length; index++) {
  45238. if (runtimeAnimations[index].animation.targetProperty === property) {
  45239. return runtimeAnimations[index].animation;
  45240. }
  45241. }
  45242. return null;
  45243. };
  45244. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  45245. var runtimeAnimations = this._runtimeAnimations;
  45246. for (var index = 0; index < runtimeAnimations.length; index++) {
  45247. if (runtimeAnimations[index].animation.targetProperty === property) {
  45248. return runtimeAnimations[index];
  45249. }
  45250. }
  45251. return null;
  45252. };
  45253. Animatable.prototype.reset = function () {
  45254. var runtimeAnimations = this._runtimeAnimations;
  45255. for (var index = 0; index < runtimeAnimations.length; index++) {
  45256. runtimeAnimations[index].reset();
  45257. }
  45258. // Reset to original value
  45259. for (index = 0; index < runtimeAnimations.length; index++) {
  45260. var animation = runtimeAnimations[index];
  45261. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  45262. }
  45263. this._localDelayOffset = null;
  45264. this._pausedDelay = null;
  45265. };
  45266. Animatable.prototype.enableBlending = function (blendingSpeed) {
  45267. var runtimeAnimations = this._runtimeAnimations;
  45268. for (var index = 0; index < runtimeAnimations.length; index++) {
  45269. runtimeAnimations[index].animation.enableBlending = true;
  45270. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  45271. }
  45272. };
  45273. Animatable.prototype.disableBlending = function () {
  45274. var runtimeAnimations = this._runtimeAnimations;
  45275. for (var index = 0; index < runtimeAnimations.length; index++) {
  45276. runtimeAnimations[index].animation.enableBlending = false;
  45277. }
  45278. };
  45279. Animatable.prototype.goToFrame = function (frame) {
  45280. var runtimeAnimations = this._runtimeAnimations;
  45281. if (runtimeAnimations[0]) {
  45282. var fps = runtimeAnimations[0].animation.framePerSecond;
  45283. var currentFrame = runtimeAnimations[0].currentFrame;
  45284. var adjustTime = frame - currentFrame;
  45285. var delay = adjustTime * 1000 / fps;
  45286. if (this._localDelayOffset === null) {
  45287. this._localDelayOffset = 0;
  45288. }
  45289. this._localDelayOffset -= delay;
  45290. }
  45291. for (var index = 0; index < runtimeAnimations.length; index++) {
  45292. runtimeAnimations[index].goToFrame(frame);
  45293. }
  45294. };
  45295. Animatable.prototype.pause = function () {
  45296. if (this._paused) {
  45297. return;
  45298. }
  45299. this._paused = true;
  45300. };
  45301. Animatable.prototype.restart = function () {
  45302. this._paused = false;
  45303. };
  45304. Animatable.prototype.stop = function (animationName) {
  45305. if (animationName) {
  45306. var idx = this._scene._activeAnimatables.indexOf(this);
  45307. if (idx > -1) {
  45308. var runtimeAnimations = this._runtimeAnimations;
  45309. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  45310. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  45311. continue;
  45312. }
  45313. runtimeAnimations[index].dispose();
  45314. runtimeAnimations.splice(index, 1);
  45315. }
  45316. if (runtimeAnimations.length == 0) {
  45317. this._scene._activeAnimatables.splice(idx, 1);
  45318. if (this.onAnimationEnd) {
  45319. this.onAnimationEnd();
  45320. }
  45321. }
  45322. }
  45323. }
  45324. else {
  45325. var index = this._scene._activeAnimatables.indexOf(this);
  45326. if (index > -1) {
  45327. this._scene._activeAnimatables.splice(index, 1);
  45328. var runtimeAnimations = this._runtimeAnimations;
  45329. for (var index = 0; index < runtimeAnimations.length; index++) {
  45330. runtimeAnimations[index].dispose();
  45331. }
  45332. if (this.onAnimationEnd) {
  45333. this.onAnimationEnd();
  45334. }
  45335. }
  45336. }
  45337. };
  45338. Animatable.prototype._animate = function (delay) {
  45339. if (this._paused) {
  45340. this.animationStarted = false;
  45341. if (this._pausedDelay === null) {
  45342. this._pausedDelay = delay;
  45343. }
  45344. return true;
  45345. }
  45346. if (this._localDelayOffset === null) {
  45347. this._localDelayOffset = delay;
  45348. this._pausedDelay = null;
  45349. }
  45350. else if (this._pausedDelay !== null) {
  45351. this._localDelayOffset += delay - this._pausedDelay;
  45352. this._pausedDelay = null;
  45353. }
  45354. // Animating
  45355. var running = false;
  45356. var runtimeAnimations = this._runtimeAnimations;
  45357. var index;
  45358. for (index = 0; index < runtimeAnimations.length; index++) {
  45359. var animation = runtimeAnimations[index];
  45360. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  45361. running = running || isRunning;
  45362. }
  45363. this.animationStarted = running;
  45364. if (!running) {
  45365. // Remove from active animatables
  45366. index = this._scene._activeAnimatables.indexOf(this);
  45367. this._scene._activeAnimatables.splice(index, 1);
  45368. // Dispose all runtime animations
  45369. for (index = 0; index < runtimeAnimations.length; index++) {
  45370. runtimeAnimations[index].dispose();
  45371. }
  45372. }
  45373. if (!running && this.onAnimationEnd) {
  45374. this.onAnimationEnd();
  45375. this.onAnimationEnd = null;
  45376. }
  45377. return running;
  45378. };
  45379. return Animatable;
  45380. }());
  45381. BABYLON.Animatable = Animatable;
  45382. })(BABYLON || (BABYLON = {}));
  45383. //# sourceMappingURL=babylon.animatable.js.map
  45384. var BABYLON;
  45385. (function (BABYLON) {
  45386. var EasingFunction = /** @class */ (function () {
  45387. function EasingFunction() {
  45388. // Properties
  45389. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  45390. }
  45391. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  45392. get: function () {
  45393. return EasingFunction._EASINGMODE_EASEIN;
  45394. },
  45395. enumerable: true,
  45396. configurable: true
  45397. });
  45398. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  45399. get: function () {
  45400. return EasingFunction._EASINGMODE_EASEOUT;
  45401. },
  45402. enumerable: true,
  45403. configurable: true
  45404. });
  45405. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  45406. get: function () {
  45407. return EasingFunction._EASINGMODE_EASEINOUT;
  45408. },
  45409. enumerable: true,
  45410. configurable: true
  45411. });
  45412. EasingFunction.prototype.setEasingMode = function (easingMode) {
  45413. var n = Math.min(Math.max(easingMode, 0), 2);
  45414. this._easingMode = n;
  45415. };
  45416. EasingFunction.prototype.getEasingMode = function () {
  45417. return this._easingMode;
  45418. };
  45419. EasingFunction.prototype.easeInCore = function (gradient) {
  45420. throw new Error('You must implement this method');
  45421. };
  45422. EasingFunction.prototype.ease = function (gradient) {
  45423. switch (this._easingMode) {
  45424. case EasingFunction.EASINGMODE_EASEIN:
  45425. return this.easeInCore(gradient);
  45426. case EasingFunction.EASINGMODE_EASEOUT:
  45427. return (1 - this.easeInCore(1 - gradient));
  45428. }
  45429. if (gradient >= 0.5) {
  45430. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  45431. }
  45432. return (this.easeInCore(gradient * 2) * 0.5);
  45433. };
  45434. //Statics
  45435. EasingFunction._EASINGMODE_EASEIN = 0;
  45436. EasingFunction._EASINGMODE_EASEOUT = 1;
  45437. EasingFunction._EASINGMODE_EASEINOUT = 2;
  45438. return EasingFunction;
  45439. }());
  45440. BABYLON.EasingFunction = EasingFunction;
  45441. var CircleEase = /** @class */ (function (_super) {
  45442. __extends(CircleEase, _super);
  45443. function CircleEase() {
  45444. return _super !== null && _super.apply(this, arguments) || this;
  45445. }
  45446. CircleEase.prototype.easeInCore = function (gradient) {
  45447. gradient = Math.max(0, Math.min(1, gradient));
  45448. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  45449. };
  45450. return CircleEase;
  45451. }(EasingFunction));
  45452. BABYLON.CircleEase = CircleEase;
  45453. var BackEase = /** @class */ (function (_super) {
  45454. __extends(BackEase, _super);
  45455. function BackEase(amplitude) {
  45456. if (amplitude === void 0) { amplitude = 1; }
  45457. var _this = _super.call(this) || this;
  45458. _this.amplitude = amplitude;
  45459. return _this;
  45460. }
  45461. BackEase.prototype.easeInCore = function (gradient) {
  45462. var num = Math.max(0, this.amplitude);
  45463. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  45464. };
  45465. return BackEase;
  45466. }(EasingFunction));
  45467. BABYLON.BackEase = BackEase;
  45468. var BounceEase = /** @class */ (function (_super) {
  45469. __extends(BounceEase, _super);
  45470. function BounceEase(bounces, bounciness) {
  45471. if (bounces === void 0) { bounces = 3; }
  45472. if (bounciness === void 0) { bounciness = 2; }
  45473. var _this = _super.call(this) || this;
  45474. _this.bounces = bounces;
  45475. _this.bounciness = bounciness;
  45476. return _this;
  45477. }
  45478. BounceEase.prototype.easeInCore = function (gradient) {
  45479. var y = Math.max(0.0, this.bounces);
  45480. var bounciness = this.bounciness;
  45481. if (bounciness <= 1.0) {
  45482. bounciness = 1.001;
  45483. }
  45484. var num9 = Math.pow(bounciness, y);
  45485. var num5 = 1.0 - bounciness;
  45486. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  45487. var num15 = gradient * num4;
  45488. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  45489. var num3 = Math.floor(num65);
  45490. var num13 = num3 + 1.0;
  45491. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  45492. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  45493. var num7 = (num8 + num12) * 0.5;
  45494. var num6 = gradient - num7;
  45495. var num2 = num7 - num8;
  45496. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  45497. };
  45498. return BounceEase;
  45499. }(EasingFunction));
  45500. BABYLON.BounceEase = BounceEase;
  45501. var CubicEase = /** @class */ (function (_super) {
  45502. __extends(CubicEase, _super);
  45503. function CubicEase() {
  45504. return _super !== null && _super.apply(this, arguments) || this;
  45505. }
  45506. CubicEase.prototype.easeInCore = function (gradient) {
  45507. return (gradient * gradient * gradient);
  45508. };
  45509. return CubicEase;
  45510. }(EasingFunction));
  45511. BABYLON.CubicEase = CubicEase;
  45512. var ElasticEase = /** @class */ (function (_super) {
  45513. __extends(ElasticEase, _super);
  45514. function ElasticEase(oscillations, springiness) {
  45515. if (oscillations === void 0) { oscillations = 3; }
  45516. if (springiness === void 0) { springiness = 3; }
  45517. var _this = _super.call(this) || this;
  45518. _this.oscillations = oscillations;
  45519. _this.springiness = springiness;
  45520. return _this;
  45521. }
  45522. ElasticEase.prototype.easeInCore = function (gradient) {
  45523. var num2;
  45524. var num3 = Math.max(0.0, this.oscillations);
  45525. var num = Math.max(0.0, this.springiness);
  45526. if (num == 0) {
  45527. num2 = gradient;
  45528. }
  45529. else {
  45530. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  45531. }
  45532. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  45533. };
  45534. return ElasticEase;
  45535. }(EasingFunction));
  45536. BABYLON.ElasticEase = ElasticEase;
  45537. var ExponentialEase = /** @class */ (function (_super) {
  45538. __extends(ExponentialEase, _super);
  45539. function ExponentialEase(exponent) {
  45540. if (exponent === void 0) { exponent = 2; }
  45541. var _this = _super.call(this) || this;
  45542. _this.exponent = exponent;
  45543. return _this;
  45544. }
  45545. ExponentialEase.prototype.easeInCore = function (gradient) {
  45546. if (this.exponent <= 0) {
  45547. return gradient;
  45548. }
  45549. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  45550. };
  45551. return ExponentialEase;
  45552. }(EasingFunction));
  45553. BABYLON.ExponentialEase = ExponentialEase;
  45554. var PowerEase = /** @class */ (function (_super) {
  45555. __extends(PowerEase, _super);
  45556. function PowerEase(power) {
  45557. if (power === void 0) { power = 2; }
  45558. var _this = _super.call(this) || this;
  45559. _this.power = power;
  45560. return _this;
  45561. }
  45562. PowerEase.prototype.easeInCore = function (gradient) {
  45563. var y = Math.max(0.0, this.power);
  45564. return Math.pow(gradient, y);
  45565. };
  45566. return PowerEase;
  45567. }(EasingFunction));
  45568. BABYLON.PowerEase = PowerEase;
  45569. var QuadraticEase = /** @class */ (function (_super) {
  45570. __extends(QuadraticEase, _super);
  45571. function QuadraticEase() {
  45572. return _super !== null && _super.apply(this, arguments) || this;
  45573. }
  45574. QuadraticEase.prototype.easeInCore = function (gradient) {
  45575. return (gradient * gradient);
  45576. };
  45577. return QuadraticEase;
  45578. }(EasingFunction));
  45579. BABYLON.QuadraticEase = QuadraticEase;
  45580. var QuarticEase = /** @class */ (function (_super) {
  45581. __extends(QuarticEase, _super);
  45582. function QuarticEase() {
  45583. return _super !== null && _super.apply(this, arguments) || this;
  45584. }
  45585. QuarticEase.prototype.easeInCore = function (gradient) {
  45586. return (gradient * gradient * gradient * gradient);
  45587. };
  45588. return QuarticEase;
  45589. }(EasingFunction));
  45590. BABYLON.QuarticEase = QuarticEase;
  45591. var QuinticEase = /** @class */ (function (_super) {
  45592. __extends(QuinticEase, _super);
  45593. function QuinticEase() {
  45594. return _super !== null && _super.apply(this, arguments) || this;
  45595. }
  45596. QuinticEase.prototype.easeInCore = function (gradient) {
  45597. return (gradient * gradient * gradient * gradient * gradient);
  45598. };
  45599. return QuinticEase;
  45600. }(EasingFunction));
  45601. BABYLON.QuinticEase = QuinticEase;
  45602. var SineEase = /** @class */ (function (_super) {
  45603. __extends(SineEase, _super);
  45604. function SineEase() {
  45605. return _super !== null && _super.apply(this, arguments) || this;
  45606. }
  45607. SineEase.prototype.easeInCore = function (gradient) {
  45608. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  45609. };
  45610. return SineEase;
  45611. }(EasingFunction));
  45612. BABYLON.SineEase = SineEase;
  45613. var BezierCurveEase = /** @class */ (function (_super) {
  45614. __extends(BezierCurveEase, _super);
  45615. function BezierCurveEase(x1, y1, x2, y2) {
  45616. if (x1 === void 0) { x1 = 0; }
  45617. if (y1 === void 0) { y1 = 0; }
  45618. if (x2 === void 0) { x2 = 1; }
  45619. if (y2 === void 0) { y2 = 1; }
  45620. var _this = _super.call(this) || this;
  45621. _this.x1 = x1;
  45622. _this.y1 = y1;
  45623. _this.x2 = x2;
  45624. _this.y2 = y2;
  45625. return _this;
  45626. }
  45627. BezierCurveEase.prototype.easeInCore = function (gradient) {
  45628. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  45629. };
  45630. return BezierCurveEase;
  45631. }(EasingFunction));
  45632. BABYLON.BezierCurveEase = BezierCurveEase;
  45633. })(BABYLON || (BABYLON = {}));
  45634. //# sourceMappingURL=babylon.easing.js.map
  45635. var BABYLON;
  45636. (function (BABYLON) {
  45637. var Condition = /** @class */ (function () {
  45638. function Condition(actionManager) {
  45639. this._actionManager = actionManager;
  45640. }
  45641. Condition.prototype.isValid = function () {
  45642. return true;
  45643. };
  45644. Condition.prototype._getProperty = function (propertyPath) {
  45645. return this._actionManager._getProperty(propertyPath);
  45646. };
  45647. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45648. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45649. };
  45650. Condition.prototype.serialize = function () {
  45651. };
  45652. Condition.prototype._serialize = function (serializedCondition) {
  45653. return {
  45654. type: 2,
  45655. children: [],
  45656. name: serializedCondition.name,
  45657. properties: serializedCondition.properties
  45658. };
  45659. };
  45660. return Condition;
  45661. }());
  45662. BABYLON.Condition = Condition;
  45663. var ValueCondition = /** @class */ (function (_super) {
  45664. __extends(ValueCondition, _super);
  45665. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45666. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45667. var _this = _super.call(this, actionManager) || this;
  45668. _this.propertyPath = propertyPath;
  45669. _this.value = value;
  45670. _this.operator = operator;
  45671. _this._target = target;
  45672. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45673. _this._property = _this._getProperty(_this.propertyPath);
  45674. return _this;
  45675. }
  45676. Object.defineProperty(ValueCondition, "IsEqual", {
  45677. get: function () {
  45678. return ValueCondition._IsEqual;
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. Object.defineProperty(ValueCondition, "IsDifferent", {
  45684. get: function () {
  45685. return ValueCondition._IsDifferent;
  45686. },
  45687. enumerable: true,
  45688. configurable: true
  45689. });
  45690. Object.defineProperty(ValueCondition, "IsGreater", {
  45691. get: function () {
  45692. return ValueCondition._IsGreater;
  45693. },
  45694. enumerable: true,
  45695. configurable: true
  45696. });
  45697. Object.defineProperty(ValueCondition, "IsLesser", {
  45698. get: function () {
  45699. return ValueCondition._IsLesser;
  45700. },
  45701. enumerable: true,
  45702. configurable: true
  45703. });
  45704. // Methods
  45705. ValueCondition.prototype.isValid = function () {
  45706. switch (this.operator) {
  45707. case ValueCondition.IsGreater:
  45708. return this._effectiveTarget[this._property] > this.value;
  45709. case ValueCondition.IsLesser:
  45710. return this._effectiveTarget[this._property] < this.value;
  45711. case ValueCondition.IsEqual:
  45712. case ValueCondition.IsDifferent:
  45713. var check;
  45714. if (this.value.equals) {
  45715. check = this.value.equals(this._effectiveTarget[this._property]);
  45716. }
  45717. else {
  45718. check = this.value === this._effectiveTarget[this._property];
  45719. }
  45720. return this.operator === ValueCondition.IsEqual ? check : !check;
  45721. }
  45722. return false;
  45723. };
  45724. ValueCondition.prototype.serialize = function () {
  45725. return this._serialize({
  45726. name: "ValueCondition",
  45727. properties: [
  45728. BABYLON.Action._GetTargetProperty(this._target),
  45729. { name: "propertyPath", value: this.propertyPath },
  45730. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45731. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45732. ]
  45733. });
  45734. };
  45735. ValueCondition.GetOperatorName = function (operator) {
  45736. switch (operator) {
  45737. case ValueCondition._IsEqual: return "IsEqual";
  45738. case ValueCondition._IsDifferent: return "IsDifferent";
  45739. case ValueCondition._IsGreater: return "IsGreater";
  45740. case ValueCondition._IsLesser: return "IsLesser";
  45741. default: return "";
  45742. }
  45743. };
  45744. // Statics
  45745. ValueCondition._IsEqual = 0;
  45746. ValueCondition._IsDifferent = 1;
  45747. ValueCondition._IsGreater = 2;
  45748. ValueCondition._IsLesser = 3;
  45749. return ValueCondition;
  45750. }(Condition));
  45751. BABYLON.ValueCondition = ValueCondition;
  45752. var PredicateCondition = /** @class */ (function (_super) {
  45753. __extends(PredicateCondition, _super);
  45754. function PredicateCondition(actionManager, predicate) {
  45755. var _this = _super.call(this, actionManager) || this;
  45756. _this.predicate = predicate;
  45757. return _this;
  45758. }
  45759. PredicateCondition.prototype.isValid = function () {
  45760. return this.predicate();
  45761. };
  45762. return PredicateCondition;
  45763. }(Condition));
  45764. BABYLON.PredicateCondition = PredicateCondition;
  45765. var StateCondition = /** @class */ (function (_super) {
  45766. __extends(StateCondition, _super);
  45767. function StateCondition(actionManager, target, value) {
  45768. var _this = _super.call(this, actionManager) || this;
  45769. _this.value = value;
  45770. _this._target = target;
  45771. return _this;
  45772. }
  45773. // Methods
  45774. StateCondition.prototype.isValid = function () {
  45775. return this._target.state === this.value;
  45776. };
  45777. StateCondition.prototype.serialize = function () {
  45778. return this._serialize({
  45779. name: "StateCondition",
  45780. properties: [
  45781. BABYLON.Action._GetTargetProperty(this._target),
  45782. { name: "value", value: this.value }
  45783. ]
  45784. });
  45785. };
  45786. return StateCondition;
  45787. }(Condition));
  45788. BABYLON.StateCondition = StateCondition;
  45789. })(BABYLON || (BABYLON = {}));
  45790. //# sourceMappingURL=babylon.condition.js.map
  45791. var BABYLON;
  45792. (function (BABYLON) {
  45793. var Action = /** @class */ (function () {
  45794. function Action(triggerOptions, condition) {
  45795. this.triggerOptions = triggerOptions;
  45796. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45797. if (triggerOptions.parameter) {
  45798. this.trigger = triggerOptions.trigger;
  45799. this._triggerParameter = triggerOptions.parameter;
  45800. }
  45801. else {
  45802. this.trigger = triggerOptions;
  45803. }
  45804. this._nextActiveAction = this;
  45805. this._condition = condition;
  45806. }
  45807. // Methods
  45808. Action.prototype._prepare = function () {
  45809. };
  45810. Action.prototype.getTriggerParameter = function () {
  45811. return this._triggerParameter;
  45812. };
  45813. Action.prototype._executeCurrent = function (evt) {
  45814. if (this._nextActiveAction._condition) {
  45815. var condition = this._nextActiveAction._condition;
  45816. var currentRenderId = this._actionManager.getScene().getRenderId();
  45817. // We cache the current evaluation for the current frame
  45818. if (condition._evaluationId === currentRenderId) {
  45819. if (!condition._currentResult) {
  45820. return;
  45821. }
  45822. }
  45823. else {
  45824. condition._evaluationId = currentRenderId;
  45825. if (!condition.isValid()) {
  45826. condition._currentResult = false;
  45827. return;
  45828. }
  45829. condition._currentResult = true;
  45830. }
  45831. }
  45832. this.onBeforeExecuteObservable.notifyObservers(this);
  45833. this._nextActiveAction.execute(evt);
  45834. this.skipToNextActiveAction();
  45835. };
  45836. Action.prototype.execute = function (evt) {
  45837. };
  45838. Action.prototype.skipToNextActiveAction = function () {
  45839. if (this._nextActiveAction._child) {
  45840. if (!this._nextActiveAction._child._actionManager) {
  45841. this._nextActiveAction._child._actionManager = this._actionManager;
  45842. }
  45843. this._nextActiveAction = this._nextActiveAction._child;
  45844. }
  45845. else {
  45846. this._nextActiveAction = this;
  45847. }
  45848. };
  45849. Action.prototype.then = function (action) {
  45850. this._child = action;
  45851. action._actionManager = this._actionManager;
  45852. action._prepare();
  45853. return action;
  45854. };
  45855. Action.prototype._getProperty = function (propertyPath) {
  45856. return this._actionManager._getProperty(propertyPath);
  45857. };
  45858. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45859. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45860. };
  45861. Action.prototype.serialize = function (parent) {
  45862. };
  45863. // Called by BABYLON.Action objects in serialize(...). Internal use
  45864. Action.prototype._serialize = function (serializedAction, parent) {
  45865. var serializationObject = {
  45866. type: 1,
  45867. children: [],
  45868. name: serializedAction.name,
  45869. properties: serializedAction.properties || []
  45870. };
  45871. // Serialize child
  45872. if (this._child) {
  45873. this._child.serialize(serializationObject);
  45874. }
  45875. // Check if "this" has a condition
  45876. if (this._condition) {
  45877. var serializedCondition = this._condition.serialize();
  45878. serializedCondition.children.push(serializationObject);
  45879. if (parent) {
  45880. parent.children.push(serializedCondition);
  45881. }
  45882. return serializedCondition;
  45883. }
  45884. if (parent) {
  45885. parent.children.push(serializationObject);
  45886. }
  45887. return serializationObject;
  45888. };
  45889. Action._SerializeValueAsString = function (value) {
  45890. if (typeof value === "number") {
  45891. return value.toString();
  45892. }
  45893. if (typeof value === "boolean") {
  45894. return value ? "true" : "false";
  45895. }
  45896. if (value instanceof BABYLON.Vector2) {
  45897. return value.x + ", " + value.y;
  45898. }
  45899. if (value instanceof BABYLON.Vector3) {
  45900. return value.x + ", " + value.y + ", " + value.z;
  45901. }
  45902. if (value instanceof BABYLON.Color3) {
  45903. return value.r + ", " + value.g + ", " + value.b;
  45904. }
  45905. if (value instanceof BABYLON.Color4) {
  45906. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45907. }
  45908. return value; // string
  45909. };
  45910. Action._GetTargetProperty = function (target) {
  45911. return {
  45912. name: "target",
  45913. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45914. : target instanceof BABYLON.Light ? "LightProperties"
  45915. : target instanceof BABYLON.Camera ? "CameraProperties"
  45916. : "SceneProperties",
  45917. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45918. };
  45919. };
  45920. return Action;
  45921. }());
  45922. BABYLON.Action = Action;
  45923. })(BABYLON || (BABYLON = {}));
  45924. //# sourceMappingURL=babylon.action.js.map
  45925. var BABYLON;
  45926. (function (BABYLON) {
  45927. /**
  45928. * ActionEvent is the event beint sent when an action is triggered.
  45929. */
  45930. var ActionEvent = /** @class */ (function () {
  45931. /**
  45932. * @param source The mesh or sprite that triggered the action.
  45933. * @param pointerX The X mouse cursor position at the time of the event
  45934. * @param pointerY The Y mouse cursor position at the time of the event
  45935. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45936. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45937. */
  45938. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45939. this.source = source;
  45940. this.pointerX = pointerX;
  45941. this.pointerY = pointerY;
  45942. this.meshUnderPointer = meshUnderPointer;
  45943. this.sourceEvent = sourceEvent;
  45944. this.additionalData = additionalData;
  45945. }
  45946. /**
  45947. * Helper function to auto-create an ActionEvent from a source mesh.
  45948. * @param source The source mesh that triggered the event
  45949. * @param evt {Event} The original (browser) event
  45950. */
  45951. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45952. var scene = source.getScene();
  45953. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45954. };
  45955. /**
  45956. * Helper function to auto-create an ActionEvent from a source mesh.
  45957. * @param source The source sprite that triggered the event
  45958. * @param scene Scene associated with the sprite
  45959. * @param evt {Event} The original (browser) event
  45960. */
  45961. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45962. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45963. };
  45964. /**
  45965. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45966. * @param scene the scene where the event occurred
  45967. * @param evt {Event} The original (browser) event
  45968. */
  45969. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45970. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45971. };
  45972. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45973. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45974. };
  45975. return ActionEvent;
  45976. }());
  45977. BABYLON.ActionEvent = ActionEvent;
  45978. /**
  45979. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45980. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45981. */
  45982. var ActionManager = /** @class */ (function () {
  45983. function ActionManager(scene) {
  45984. // Members
  45985. this.actions = new Array();
  45986. this.hoverCursor = '';
  45987. this._scene = scene;
  45988. scene._actionManagers.push(this);
  45989. }
  45990. Object.defineProperty(ActionManager, "NothingTrigger", {
  45991. get: function () {
  45992. return ActionManager._NothingTrigger;
  45993. },
  45994. enumerable: true,
  45995. configurable: true
  45996. });
  45997. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45998. get: function () {
  45999. return ActionManager._OnPickTrigger;
  46000. },
  46001. enumerable: true,
  46002. configurable: true
  46003. });
  46004. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46005. get: function () {
  46006. return ActionManager._OnLeftPickTrigger;
  46007. },
  46008. enumerable: true,
  46009. configurable: true
  46010. });
  46011. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46012. get: function () {
  46013. return ActionManager._OnRightPickTrigger;
  46014. },
  46015. enumerable: true,
  46016. configurable: true
  46017. });
  46018. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46019. get: function () {
  46020. return ActionManager._OnCenterPickTrigger;
  46021. },
  46022. enumerable: true,
  46023. configurable: true
  46024. });
  46025. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46026. get: function () {
  46027. return ActionManager._OnPickDownTrigger;
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46033. get: function () {
  46034. return ActionManager._OnDoublePickTrigger;
  46035. },
  46036. enumerable: true,
  46037. configurable: true
  46038. });
  46039. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46040. get: function () {
  46041. return ActionManager._OnPickUpTrigger;
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46047. /// This trigger will only be raised if you also declared a OnPickDown
  46048. get: function () {
  46049. return ActionManager._OnPickOutTrigger;
  46050. },
  46051. enumerable: true,
  46052. configurable: true
  46053. });
  46054. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46055. get: function () {
  46056. return ActionManager._OnLongPressTrigger;
  46057. },
  46058. enumerable: true,
  46059. configurable: true
  46060. });
  46061. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46062. get: function () {
  46063. return ActionManager._OnPointerOverTrigger;
  46064. },
  46065. enumerable: true,
  46066. configurable: true
  46067. });
  46068. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46069. get: function () {
  46070. return ActionManager._OnPointerOutTrigger;
  46071. },
  46072. enumerable: true,
  46073. configurable: true
  46074. });
  46075. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46076. get: function () {
  46077. return ActionManager._OnEveryFrameTrigger;
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46083. get: function () {
  46084. return ActionManager._OnIntersectionEnterTrigger;
  46085. },
  46086. enumerable: true,
  46087. configurable: true
  46088. });
  46089. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46090. get: function () {
  46091. return ActionManager._OnIntersectionExitTrigger;
  46092. },
  46093. enumerable: true,
  46094. configurable: true
  46095. });
  46096. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46097. get: function () {
  46098. return ActionManager._OnKeyDownTrigger;
  46099. },
  46100. enumerable: true,
  46101. configurable: true
  46102. });
  46103. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46104. get: function () {
  46105. return ActionManager._OnKeyUpTrigger;
  46106. },
  46107. enumerable: true,
  46108. configurable: true
  46109. });
  46110. // Methods
  46111. ActionManager.prototype.dispose = function () {
  46112. var index = this._scene._actionManagers.indexOf(this);
  46113. for (var i = 0; i < this.actions.length; i++) {
  46114. var action = this.actions[i];
  46115. ActionManager.Triggers[action.trigger]--;
  46116. if (ActionManager.Triggers[action.trigger] === 0) {
  46117. delete ActionManager.Triggers[action.trigger];
  46118. }
  46119. }
  46120. if (index > -1) {
  46121. this._scene._actionManagers.splice(index, 1);
  46122. }
  46123. };
  46124. ActionManager.prototype.getScene = function () {
  46125. return this._scene;
  46126. };
  46127. /**
  46128. * Does this action manager handles actions of any of the given triggers
  46129. * @param {number[]} triggers - the triggers to be tested
  46130. * @return {boolean} whether one (or more) of the triggers is handeled
  46131. */
  46132. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46133. for (var index = 0; index < this.actions.length; index++) {
  46134. var action = this.actions[index];
  46135. if (triggers.indexOf(action.trigger) > -1) {
  46136. return true;
  46137. }
  46138. }
  46139. return false;
  46140. };
  46141. /**
  46142. * Does this action manager handles actions of a given trigger
  46143. * @param {number} trigger - the trigger to be tested
  46144. * @return {boolean} whether the trigger is handeled
  46145. */
  46146. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46147. for (var index = 0; index < this.actions.length; index++) {
  46148. var action = this.actions[index];
  46149. if (action.trigger === trigger) {
  46150. return true;
  46151. }
  46152. }
  46153. return false;
  46154. };
  46155. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46156. /**
  46157. * Does this action manager has pointer triggers
  46158. * @return {boolean} whether or not it has pointer triggers
  46159. */
  46160. get: function () {
  46161. for (var index = 0; index < this.actions.length; index++) {
  46162. var action = this.actions[index];
  46163. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46164. return true;
  46165. }
  46166. }
  46167. return false;
  46168. },
  46169. enumerable: true,
  46170. configurable: true
  46171. });
  46172. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46173. /**
  46174. * Does this action manager has pick triggers
  46175. * @return {boolean} whether or not it has pick triggers
  46176. */
  46177. get: function () {
  46178. for (var index = 0; index < this.actions.length; index++) {
  46179. var action = this.actions[index];
  46180. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46181. return true;
  46182. }
  46183. }
  46184. return false;
  46185. },
  46186. enumerable: true,
  46187. configurable: true
  46188. });
  46189. Object.defineProperty(ActionManager, "HasTriggers", {
  46190. /**
  46191. * Does exist one action manager with at least one trigger
  46192. * @return {boolean} whether or not it exists one action manager with one trigger
  46193. **/
  46194. get: function () {
  46195. for (var t in ActionManager.Triggers) {
  46196. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46197. return true;
  46198. }
  46199. }
  46200. return false;
  46201. },
  46202. enumerable: true,
  46203. configurable: true
  46204. });
  46205. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46206. /**
  46207. * Does exist one action manager with at least one pick trigger
  46208. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46209. **/
  46210. get: function () {
  46211. for (var t in ActionManager.Triggers) {
  46212. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46213. var t_int = parseInt(t);
  46214. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46215. return true;
  46216. }
  46217. }
  46218. }
  46219. return false;
  46220. },
  46221. enumerable: true,
  46222. configurable: true
  46223. });
  46224. /**
  46225. * Does exist one action manager that handles actions of a given trigger
  46226. * @param {number} trigger - the trigger to be tested
  46227. * @return {boolean} whether the trigger is handeled by at least one action manager
  46228. **/
  46229. ActionManager.HasSpecificTrigger = function (trigger) {
  46230. for (var t in ActionManager.Triggers) {
  46231. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46232. var t_int = parseInt(t);
  46233. if (t_int === trigger) {
  46234. return true;
  46235. }
  46236. }
  46237. }
  46238. return false;
  46239. };
  46240. /**
  46241. * Registers an action to this action manager
  46242. * @param {BABYLON.Action} action - the action to be registered
  46243. * @return {BABYLON.Action} the action amended (prepared) after registration
  46244. */
  46245. ActionManager.prototype.registerAction = function (action) {
  46246. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46247. if (this.getScene().actionManager !== this) {
  46248. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46249. return null;
  46250. }
  46251. }
  46252. this.actions.push(action);
  46253. if (ActionManager.Triggers[action.trigger]) {
  46254. ActionManager.Triggers[action.trigger]++;
  46255. }
  46256. else {
  46257. ActionManager.Triggers[action.trigger] = 1;
  46258. }
  46259. action._actionManager = this;
  46260. action._prepare();
  46261. return action;
  46262. };
  46263. /**
  46264. * Unregisters an action to this action manager
  46265. * @param action The action to be unregistered
  46266. * @return whether the action has been unregistered
  46267. */
  46268. ActionManager.prototype.unregisterAction = function (action) {
  46269. var index = this.actions.indexOf(action);
  46270. if (index !== -1) {
  46271. this.actions.splice(index, 1);
  46272. ActionManager.Triggers[action.trigger] -= 1;
  46273. if (ActionManager.Triggers[action.trigger] === 0) {
  46274. delete ActionManager.Triggers[action.trigger];
  46275. }
  46276. delete action._actionManager;
  46277. return true;
  46278. }
  46279. return false;
  46280. };
  46281. /**
  46282. * Process a specific trigger
  46283. * @param {number} trigger - the trigger to process
  46284. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46285. */
  46286. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46287. for (var index = 0; index < this.actions.length; index++) {
  46288. var action = this.actions[index];
  46289. if (action.trigger === trigger) {
  46290. if (evt) {
  46291. if (trigger === ActionManager.OnKeyUpTrigger
  46292. || trigger === ActionManager.OnKeyDownTrigger) {
  46293. var parameter = action.getTriggerParameter();
  46294. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46295. if (!parameter.toLowerCase) {
  46296. continue;
  46297. }
  46298. var lowerCase = parameter.toLowerCase();
  46299. if (lowerCase !== evt.sourceEvent.key) {
  46300. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46301. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46302. if (actualkey !== lowerCase) {
  46303. continue;
  46304. }
  46305. }
  46306. }
  46307. }
  46308. }
  46309. action._executeCurrent(evt);
  46310. }
  46311. }
  46312. };
  46313. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46314. var properties = propertyPath.split(".");
  46315. for (var index = 0; index < properties.length - 1; index++) {
  46316. target = target[properties[index]];
  46317. }
  46318. return target;
  46319. };
  46320. ActionManager.prototype._getProperty = function (propertyPath) {
  46321. var properties = propertyPath.split(".");
  46322. return properties[properties.length - 1];
  46323. };
  46324. ActionManager.prototype.serialize = function (name) {
  46325. var root = {
  46326. children: new Array(),
  46327. name: name,
  46328. type: 3,
  46329. properties: new Array() // Empty for root but required
  46330. };
  46331. for (var i = 0; i < this.actions.length; i++) {
  46332. var triggerObject = {
  46333. type: 0,
  46334. children: new Array(),
  46335. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46336. properties: new Array()
  46337. };
  46338. var triggerOptions = this.actions[i].triggerOptions;
  46339. if (triggerOptions && typeof triggerOptions !== "number") {
  46340. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46341. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46342. }
  46343. else {
  46344. var parameter = {};
  46345. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46346. if (triggerOptions.parameter.mesh) {
  46347. parameter._meshId = triggerOptions.parameter.mesh.id;
  46348. }
  46349. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46350. }
  46351. }
  46352. // Serialize child action, recursively
  46353. this.actions[i].serialize(triggerObject);
  46354. // Add serialized trigger
  46355. root.children.push(triggerObject);
  46356. }
  46357. return root;
  46358. };
  46359. ActionManager.Parse = function (parsedActions, object, scene) {
  46360. var actionManager = new ActionManager(scene);
  46361. if (object === null)
  46362. scene.actionManager = actionManager;
  46363. else
  46364. object.actionManager = actionManager;
  46365. // instanciate a new object
  46366. var instanciate = function (name, params) {
  46367. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  46368. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  46369. newInstance.constructor.apply(newInstance, params);
  46370. return newInstance;
  46371. };
  46372. var parseParameter = function (name, value, target, propertyPath) {
  46373. if (propertyPath === null) {
  46374. // String, boolean or float
  46375. var floatValue = parseFloat(value);
  46376. if (value === "true" || value === "false")
  46377. return value === "true";
  46378. else
  46379. return isNaN(floatValue) ? value : floatValue;
  46380. }
  46381. var effectiveTarget = propertyPath.split(".");
  46382. var values = value.split(",");
  46383. // Get effective Target
  46384. for (var i = 0; i < effectiveTarget.length; i++) {
  46385. target = target[effectiveTarget[i]];
  46386. }
  46387. // Return appropriate value with its type
  46388. if (typeof (target) === "boolean")
  46389. return values[0] === "true";
  46390. if (typeof (target) === "string")
  46391. return values[0];
  46392. // Parameters with multiple values such as Vector3 etc.
  46393. var split = new Array();
  46394. for (var i = 0; i < values.length; i++)
  46395. split.push(parseFloat(values[i]));
  46396. if (target instanceof BABYLON.Vector3)
  46397. return BABYLON.Vector3.FromArray(split);
  46398. if (target instanceof BABYLON.Vector4)
  46399. return BABYLON.Vector4.FromArray(split);
  46400. if (target instanceof BABYLON.Color3)
  46401. return BABYLON.Color3.FromArray(split);
  46402. if (target instanceof BABYLON.Color4)
  46403. return BABYLON.Color4.FromArray(split);
  46404. return parseFloat(values[0]);
  46405. };
  46406. // traverse graph per trigger
  46407. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46408. if (combineArray === void 0) { combineArray = null; }
  46409. if (parsedAction.detached)
  46410. return;
  46411. var parameters = new Array();
  46412. var target = null;
  46413. var propertyPath = null;
  46414. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46415. // Parameters
  46416. if (parsedAction.type === 2)
  46417. parameters.push(actionManager);
  46418. else
  46419. parameters.push(trigger);
  46420. if (combine) {
  46421. var actions = new Array();
  46422. for (var j = 0; j < parsedAction.combine.length; j++) {
  46423. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46424. }
  46425. parameters.push(actions);
  46426. }
  46427. else {
  46428. for (var i = 0; i < parsedAction.properties.length; i++) {
  46429. var value = parsedAction.properties[i].value;
  46430. var name = parsedAction.properties[i].name;
  46431. var targetType = parsedAction.properties[i].targetType;
  46432. if (name === "target")
  46433. if (targetType !== null && targetType === "SceneProperties")
  46434. value = target = scene;
  46435. else
  46436. value = target = scene.getNodeByName(value);
  46437. else if (name === "parent")
  46438. value = scene.getNodeByName(value);
  46439. else if (name === "sound")
  46440. value = scene.getSoundByName(value);
  46441. else if (name !== "propertyPath") {
  46442. if (parsedAction.type === 2 && name === "operator")
  46443. value = BABYLON.ValueCondition[value];
  46444. else
  46445. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46446. }
  46447. else {
  46448. propertyPath = value;
  46449. }
  46450. parameters.push(value);
  46451. }
  46452. }
  46453. if (combineArray === null) {
  46454. parameters.push(condition);
  46455. }
  46456. else {
  46457. parameters.push(null);
  46458. }
  46459. // If interpolate value action
  46460. if (parsedAction.name === "InterpolateValueAction") {
  46461. var param = parameters[parameters.length - 2];
  46462. parameters[parameters.length - 1] = param;
  46463. parameters[parameters.length - 2] = condition;
  46464. }
  46465. // Action or condition(s) and not CombineAction
  46466. var newAction = instanciate(parsedAction.name, parameters);
  46467. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46468. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46469. if (action)
  46470. action.then(nothing);
  46471. else
  46472. actionManager.registerAction(nothing);
  46473. action = nothing;
  46474. }
  46475. if (combineArray === null) {
  46476. if (newAction instanceof BABYLON.Condition) {
  46477. condition = newAction;
  46478. newAction = action;
  46479. }
  46480. else {
  46481. condition = null;
  46482. if (action)
  46483. action.then(newAction);
  46484. else
  46485. actionManager.registerAction(newAction);
  46486. }
  46487. }
  46488. else {
  46489. combineArray.push(newAction);
  46490. }
  46491. for (var i = 0; i < parsedAction.children.length; i++)
  46492. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46493. };
  46494. // triggers
  46495. for (var i = 0; i < parsedActions.children.length; i++) {
  46496. var triggerParams;
  46497. var trigger = parsedActions.children[i];
  46498. if (trigger.properties.length > 0) {
  46499. var param = trigger.properties[0].value;
  46500. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46501. if (value._meshId) {
  46502. value.mesh = scene.getMeshByID(value._meshId);
  46503. }
  46504. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  46505. }
  46506. else
  46507. triggerParams = ActionManager[trigger.name];
  46508. for (var j = 0; j < trigger.children.length; j++) {
  46509. if (!trigger.detached)
  46510. traverse(trigger.children[j], triggerParams, null, null);
  46511. }
  46512. }
  46513. };
  46514. ActionManager.GetTriggerName = function (trigger) {
  46515. switch (trigger) {
  46516. case 0: return "NothingTrigger";
  46517. case 1: return "OnPickTrigger";
  46518. case 2: return "OnLeftPickTrigger";
  46519. case 3: return "OnRightPickTrigger";
  46520. case 4: return "OnCenterPickTrigger";
  46521. case 5: return "OnPickDownTrigger";
  46522. case 6: return "OnPickUpTrigger";
  46523. case 7: return "OnLongPressTrigger";
  46524. case 8: return "OnPointerOverTrigger";
  46525. case 9: return "OnPointerOutTrigger";
  46526. case 10: return "OnEveryFrameTrigger";
  46527. case 11: return "OnIntersectionEnterTrigger";
  46528. case 12: return "OnIntersectionExitTrigger";
  46529. case 13: return "OnKeyDownTrigger";
  46530. case 14: return "OnKeyUpTrigger";
  46531. case 15: return "OnPickOutTrigger";
  46532. default: return "";
  46533. }
  46534. };
  46535. // Statics
  46536. ActionManager._NothingTrigger = 0;
  46537. ActionManager._OnPickTrigger = 1;
  46538. ActionManager._OnLeftPickTrigger = 2;
  46539. ActionManager._OnRightPickTrigger = 3;
  46540. ActionManager._OnCenterPickTrigger = 4;
  46541. ActionManager._OnPickDownTrigger = 5;
  46542. ActionManager._OnDoublePickTrigger = 6;
  46543. ActionManager._OnPickUpTrigger = 7;
  46544. ActionManager._OnLongPressTrigger = 8;
  46545. ActionManager._OnPointerOverTrigger = 9;
  46546. ActionManager._OnPointerOutTrigger = 10;
  46547. ActionManager._OnEveryFrameTrigger = 11;
  46548. ActionManager._OnIntersectionEnterTrigger = 12;
  46549. ActionManager._OnIntersectionExitTrigger = 13;
  46550. ActionManager._OnKeyDownTrigger = 14;
  46551. ActionManager._OnKeyUpTrigger = 15;
  46552. ActionManager._OnPickOutTrigger = 16;
  46553. ActionManager.Triggers = {};
  46554. return ActionManager;
  46555. }());
  46556. BABYLON.ActionManager = ActionManager;
  46557. })(BABYLON || (BABYLON = {}));
  46558. //# sourceMappingURL=babylon.actionManager.js.map
  46559. var BABYLON;
  46560. (function (BABYLON) {
  46561. var InterpolateValueAction = /** @class */ (function (_super) {
  46562. __extends(InterpolateValueAction, _super);
  46563. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46564. if (duration === void 0) { duration = 1000; }
  46565. var _this = _super.call(this, triggerOptions, condition) || this;
  46566. _this.propertyPath = propertyPath;
  46567. _this.value = value;
  46568. _this.duration = duration;
  46569. _this.stopOtherAnimations = stopOtherAnimations;
  46570. _this.onInterpolationDone = onInterpolationDone;
  46571. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  46572. _this._target = _this._effectiveTarget = target;
  46573. return _this;
  46574. }
  46575. InterpolateValueAction.prototype._prepare = function () {
  46576. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46577. this._property = this._getProperty(this.propertyPath);
  46578. };
  46579. InterpolateValueAction.prototype.execute = function () {
  46580. var _this = this;
  46581. var scene = this._actionManager.getScene();
  46582. var keys = [
  46583. {
  46584. frame: 0,
  46585. value: this._effectiveTarget[this._property]
  46586. }, {
  46587. frame: 100,
  46588. value: this.value
  46589. }
  46590. ];
  46591. var dataType;
  46592. if (typeof this.value === "number") {
  46593. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46594. }
  46595. else if (this.value instanceof BABYLON.Color3) {
  46596. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46597. }
  46598. else if (this.value instanceof BABYLON.Vector3) {
  46599. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46600. }
  46601. else if (this.value instanceof BABYLON.Matrix) {
  46602. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46603. }
  46604. else if (this.value instanceof BABYLON.Quaternion) {
  46605. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46606. }
  46607. else {
  46608. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46609. return;
  46610. }
  46611. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46612. animation.setKeys(keys);
  46613. if (this.stopOtherAnimations) {
  46614. scene.stopAnimation(this._effectiveTarget);
  46615. }
  46616. var wrapper = function () {
  46617. _this.onInterpolationDoneObservable.notifyObservers(_this);
  46618. if (_this.onInterpolationDone) {
  46619. _this.onInterpolationDone();
  46620. }
  46621. };
  46622. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  46623. };
  46624. InterpolateValueAction.prototype.serialize = function (parent) {
  46625. return _super.prototype._serialize.call(this, {
  46626. name: "InterpolateValueAction",
  46627. properties: [
  46628. BABYLON.Action._GetTargetProperty(this._target),
  46629. { name: "propertyPath", value: this.propertyPath },
  46630. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46631. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46632. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46633. ]
  46634. }, parent);
  46635. };
  46636. return InterpolateValueAction;
  46637. }(BABYLON.Action));
  46638. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46639. })(BABYLON || (BABYLON = {}));
  46640. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46641. var BABYLON;
  46642. (function (BABYLON) {
  46643. var SwitchBooleanAction = /** @class */ (function (_super) {
  46644. __extends(SwitchBooleanAction, _super);
  46645. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46646. var _this = _super.call(this, triggerOptions, condition) || this;
  46647. _this.propertyPath = propertyPath;
  46648. _this._target = _this._effectiveTarget = target;
  46649. return _this;
  46650. }
  46651. SwitchBooleanAction.prototype._prepare = function () {
  46652. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46653. this._property = this._getProperty(this.propertyPath);
  46654. };
  46655. SwitchBooleanAction.prototype.execute = function () {
  46656. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46657. };
  46658. SwitchBooleanAction.prototype.serialize = function (parent) {
  46659. return _super.prototype._serialize.call(this, {
  46660. name: "SwitchBooleanAction",
  46661. properties: [
  46662. BABYLON.Action._GetTargetProperty(this._target),
  46663. { name: "propertyPath", value: this.propertyPath }
  46664. ]
  46665. }, parent);
  46666. };
  46667. return SwitchBooleanAction;
  46668. }(BABYLON.Action));
  46669. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46670. var SetStateAction = /** @class */ (function (_super) {
  46671. __extends(SetStateAction, _super);
  46672. function SetStateAction(triggerOptions, target, value, condition) {
  46673. var _this = _super.call(this, triggerOptions, condition) || this;
  46674. _this.value = value;
  46675. _this._target = target;
  46676. return _this;
  46677. }
  46678. SetStateAction.prototype.execute = function () {
  46679. this._target.state = this.value;
  46680. };
  46681. SetStateAction.prototype.serialize = function (parent) {
  46682. return _super.prototype._serialize.call(this, {
  46683. name: "SetStateAction",
  46684. properties: [
  46685. BABYLON.Action._GetTargetProperty(this._target),
  46686. { name: "value", value: this.value }
  46687. ]
  46688. }, parent);
  46689. };
  46690. return SetStateAction;
  46691. }(BABYLON.Action));
  46692. BABYLON.SetStateAction = SetStateAction;
  46693. var SetValueAction = /** @class */ (function (_super) {
  46694. __extends(SetValueAction, _super);
  46695. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46696. var _this = _super.call(this, triggerOptions, condition) || this;
  46697. _this.propertyPath = propertyPath;
  46698. _this.value = value;
  46699. _this._target = _this._effectiveTarget = target;
  46700. return _this;
  46701. }
  46702. SetValueAction.prototype._prepare = function () {
  46703. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46704. this._property = this._getProperty(this.propertyPath);
  46705. };
  46706. SetValueAction.prototype.execute = function () {
  46707. this._effectiveTarget[this._property] = this.value;
  46708. if (this._target.markAsDirty) {
  46709. this._target.markAsDirty(this._property);
  46710. }
  46711. };
  46712. SetValueAction.prototype.serialize = function (parent) {
  46713. return _super.prototype._serialize.call(this, {
  46714. name: "SetValueAction",
  46715. properties: [
  46716. BABYLON.Action._GetTargetProperty(this._target),
  46717. { name: "propertyPath", value: this.propertyPath },
  46718. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46719. ]
  46720. }, parent);
  46721. };
  46722. return SetValueAction;
  46723. }(BABYLON.Action));
  46724. BABYLON.SetValueAction = SetValueAction;
  46725. var IncrementValueAction = /** @class */ (function (_super) {
  46726. __extends(IncrementValueAction, _super);
  46727. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46728. var _this = _super.call(this, triggerOptions, condition) || this;
  46729. _this.propertyPath = propertyPath;
  46730. _this.value = value;
  46731. _this._target = _this._effectiveTarget = target;
  46732. return _this;
  46733. }
  46734. IncrementValueAction.prototype._prepare = function () {
  46735. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46736. this._property = this._getProperty(this.propertyPath);
  46737. if (typeof this._effectiveTarget[this._property] !== "number") {
  46738. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46739. }
  46740. };
  46741. IncrementValueAction.prototype.execute = function () {
  46742. this._effectiveTarget[this._property] += this.value;
  46743. if (this._target.markAsDirty) {
  46744. this._target.markAsDirty(this._property);
  46745. }
  46746. };
  46747. IncrementValueAction.prototype.serialize = function (parent) {
  46748. return _super.prototype._serialize.call(this, {
  46749. name: "IncrementValueAction",
  46750. properties: [
  46751. BABYLON.Action._GetTargetProperty(this._target),
  46752. { name: "propertyPath", value: this.propertyPath },
  46753. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46754. ]
  46755. }, parent);
  46756. };
  46757. return IncrementValueAction;
  46758. }(BABYLON.Action));
  46759. BABYLON.IncrementValueAction = IncrementValueAction;
  46760. var PlayAnimationAction = /** @class */ (function (_super) {
  46761. __extends(PlayAnimationAction, _super);
  46762. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46763. var _this = _super.call(this, triggerOptions, condition) || this;
  46764. _this.from = from;
  46765. _this.to = to;
  46766. _this.loop = loop;
  46767. _this._target = target;
  46768. return _this;
  46769. }
  46770. PlayAnimationAction.prototype._prepare = function () {
  46771. };
  46772. PlayAnimationAction.prototype.execute = function () {
  46773. var scene = this._actionManager.getScene();
  46774. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46775. };
  46776. PlayAnimationAction.prototype.serialize = function (parent) {
  46777. return _super.prototype._serialize.call(this, {
  46778. name: "PlayAnimationAction",
  46779. properties: [
  46780. BABYLON.Action._GetTargetProperty(this._target),
  46781. { name: "from", value: String(this.from) },
  46782. { name: "to", value: String(this.to) },
  46783. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46784. ]
  46785. }, parent);
  46786. };
  46787. return PlayAnimationAction;
  46788. }(BABYLON.Action));
  46789. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46790. var StopAnimationAction = /** @class */ (function (_super) {
  46791. __extends(StopAnimationAction, _super);
  46792. function StopAnimationAction(triggerOptions, target, condition) {
  46793. var _this = _super.call(this, triggerOptions, condition) || this;
  46794. _this._target = target;
  46795. return _this;
  46796. }
  46797. StopAnimationAction.prototype._prepare = function () {
  46798. };
  46799. StopAnimationAction.prototype.execute = function () {
  46800. var scene = this._actionManager.getScene();
  46801. scene.stopAnimation(this._target);
  46802. };
  46803. StopAnimationAction.prototype.serialize = function (parent) {
  46804. return _super.prototype._serialize.call(this, {
  46805. name: "StopAnimationAction",
  46806. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46807. }, parent);
  46808. };
  46809. return StopAnimationAction;
  46810. }(BABYLON.Action));
  46811. BABYLON.StopAnimationAction = StopAnimationAction;
  46812. var DoNothingAction = /** @class */ (function (_super) {
  46813. __extends(DoNothingAction, _super);
  46814. function DoNothingAction(triggerOptions, condition) {
  46815. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46816. return _super.call(this, triggerOptions, condition) || this;
  46817. }
  46818. DoNothingAction.prototype.execute = function () {
  46819. };
  46820. DoNothingAction.prototype.serialize = function (parent) {
  46821. return _super.prototype._serialize.call(this, {
  46822. name: "DoNothingAction",
  46823. properties: []
  46824. }, parent);
  46825. };
  46826. return DoNothingAction;
  46827. }(BABYLON.Action));
  46828. BABYLON.DoNothingAction = DoNothingAction;
  46829. var CombineAction = /** @class */ (function (_super) {
  46830. __extends(CombineAction, _super);
  46831. function CombineAction(triggerOptions, children, condition) {
  46832. var _this = _super.call(this, triggerOptions, condition) || this;
  46833. _this.children = children;
  46834. return _this;
  46835. }
  46836. CombineAction.prototype._prepare = function () {
  46837. for (var index = 0; index < this.children.length; index++) {
  46838. this.children[index]._actionManager = this._actionManager;
  46839. this.children[index]._prepare();
  46840. }
  46841. };
  46842. CombineAction.prototype.execute = function (evt) {
  46843. for (var index = 0; index < this.children.length; index++) {
  46844. this.children[index].execute(evt);
  46845. }
  46846. };
  46847. CombineAction.prototype.serialize = function (parent) {
  46848. var serializationObject = _super.prototype._serialize.call(this, {
  46849. name: "CombineAction",
  46850. properties: [],
  46851. combine: []
  46852. }, parent);
  46853. for (var i = 0; i < this.children.length; i++) {
  46854. serializationObject.combine.push(this.children[i].serialize(null));
  46855. }
  46856. return serializationObject;
  46857. };
  46858. return CombineAction;
  46859. }(BABYLON.Action));
  46860. BABYLON.CombineAction = CombineAction;
  46861. var ExecuteCodeAction = /** @class */ (function (_super) {
  46862. __extends(ExecuteCodeAction, _super);
  46863. function ExecuteCodeAction(triggerOptions, func, condition) {
  46864. var _this = _super.call(this, triggerOptions, condition) || this;
  46865. _this.func = func;
  46866. return _this;
  46867. }
  46868. ExecuteCodeAction.prototype.execute = function (evt) {
  46869. this.func(evt);
  46870. };
  46871. return ExecuteCodeAction;
  46872. }(BABYLON.Action));
  46873. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46874. var SetParentAction = /** @class */ (function (_super) {
  46875. __extends(SetParentAction, _super);
  46876. function SetParentAction(triggerOptions, target, parent, condition) {
  46877. var _this = _super.call(this, triggerOptions, condition) || this;
  46878. _this._target = target;
  46879. _this._parent = parent;
  46880. return _this;
  46881. }
  46882. SetParentAction.prototype._prepare = function () {
  46883. };
  46884. SetParentAction.prototype.execute = function () {
  46885. if (this._target.parent === this._parent) {
  46886. return;
  46887. }
  46888. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46889. invertParentWorldMatrix.invert();
  46890. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46891. this._target.parent = this._parent;
  46892. };
  46893. SetParentAction.prototype.serialize = function (parent) {
  46894. return _super.prototype._serialize.call(this, {
  46895. name: "SetParentAction",
  46896. properties: [
  46897. BABYLON.Action._GetTargetProperty(this._target),
  46898. BABYLON.Action._GetTargetProperty(this._parent),
  46899. ]
  46900. }, parent);
  46901. };
  46902. return SetParentAction;
  46903. }(BABYLON.Action));
  46904. BABYLON.SetParentAction = SetParentAction;
  46905. var PlaySoundAction = /** @class */ (function (_super) {
  46906. __extends(PlaySoundAction, _super);
  46907. function PlaySoundAction(triggerOptions, sound, condition) {
  46908. var _this = _super.call(this, triggerOptions, condition) || this;
  46909. _this._sound = sound;
  46910. return _this;
  46911. }
  46912. PlaySoundAction.prototype._prepare = function () {
  46913. };
  46914. PlaySoundAction.prototype.execute = function () {
  46915. if (this._sound !== undefined)
  46916. this._sound.play();
  46917. };
  46918. PlaySoundAction.prototype.serialize = function (parent) {
  46919. return _super.prototype._serialize.call(this, {
  46920. name: "PlaySoundAction",
  46921. properties: [{ name: "sound", value: this._sound.name }]
  46922. }, parent);
  46923. };
  46924. return PlaySoundAction;
  46925. }(BABYLON.Action));
  46926. BABYLON.PlaySoundAction = PlaySoundAction;
  46927. var StopSoundAction = /** @class */ (function (_super) {
  46928. __extends(StopSoundAction, _super);
  46929. function StopSoundAction(triggerOptions, sound, condition) {
  46930. var _this = _super.call(this, triggerOptions, condition) || this;
  46931. _this._sound = sound;
  46932. return _this;
  46933. }
  46934. StopSoundAction.prototype._prepare = function () {
  46935. };
  46936. StopSoundAction.prototype.execute = function () {
  46937. if (this._sound !== undefined)
  46938. this._sound.stop();
  46939. };
  46940. StopSoundAction.prototype.serialize = function (parent) {
  46941. return _super.prototype._serialize.call(this, {
  46942. name: "StopSoundAction",
  46943. properties: [{ name: "sound", value: this._sound.name }]
  46944. }, parent);
  46945. };
  46946. return StopSoundAction;
  46947. }(BABYLON.Action));
  46948. BABYLON.StopSoundAction = StopSoundAction;
  46949. })(BABYLON || (BABYLON = {}));
  46950. //# sourceMappingURL=babylon.directActions.js.map
  46951. var BABYLON;
  46952. (function (BABYLON) {
  46953. var SpriteManager = /** @class */ (function () {
  46954. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46955. if (epsilon === void 0) { epsilon = 0.01; }
  46956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46957. this.name = name;
  46958. this.sprites = new Array();
  46959. this.renderingGroupId = 0;
  46960. this.layerMask = 0x0FFFFFFF;
  46961. this.fogEnabled = true;
  46962. this.isPickable = false;
  46963. /**
  46964. * An event triggered when the manager is disposed.
  46965. * @type {BABYLON.Observable}
  46966. */
  46967. this.onDisposeObservable = new BABYLON.Observable();
  46968. this._vertexBuffers = {};
  46969. this._capacity = capacity;
  46970. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46971. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46972. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46973. if (cellSize.width && cellSize.height) {
  46974. this.cellWidth = cellSize.width;
  46975. this.cellHeight = cellSize.height;
  46976. }
  46977. else if (cellSize !== undefined) {
  46978. this.cellWidth = cellSize;
  46979. this.cellHeight = cellSize;
  46980. }
  46981. else {
  46982. return;
  46983. }
  46984. this._epsilon = epsilon;
  46985. this._scene = scene;
  46986. this._scene.spriteManagers.push(this);
  46987. var indices = [];
  46988. var index = 0;
  46989. for (var count = 0; count < capacity; count++) {
  46990. indices.push(index);
  46991. indices.push(index + 1);
  46992. indices.push(index + 2);
  46993. indices.push(index);
  46994. indices.push(index + 2);
  46995. indices.push(index + 3);
  46996. index += 4;
  46997. }
  46998. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46999. // VBO
  47000. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  47001. this._vertexData = new Float32Array(capacity * 16 * 4);
  47002. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  47003. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  47004. var options = this._buffer.createVertexBuffer("options", 4, 4);
  47005. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  47006. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  47007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47008. this._vertexBuffers["options"] = options;
  47009. this._vertexBuffers["cellInfo"] = cellInfo;
  47010. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47011. // Effects
  47012. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  47013. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  47014. }
  47015. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  47016. set: function (callback) {
  47017. if (this._onDisposeObserver) {
  47018. this.onDisposeObservable.remove(this._onDisposeObserver);
  47019. }
  47020. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47021. },
  47022. enumerable: true,
  47023. configurable: true
  47024. });
  47025. Object.defineProperty(SpriteManager.prototype, "texture", {
  47026. get: function () {
  47027. return this._spriteTexture;
  47028. },
  47029. set: function (value) {
  47030. this._spriteTexture = value;
  47031. },
  47032. enumerable: true,
  47033. configurable: true
  47034. });
  47035. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  47036. var arrayOffset = index * 16;
  47037. if (offsetX === 0)
  47038. offsetX = this._epsilon;
  47039. else if (offsetX === 1)
  47040. offsetX = 1 - this._epsilon;
  47041. if (offsetY === 0)
  47042. offsetY = this._epsilon;
  47043. else if (offsetY === 1)
  47044. offsetY = 1 - this._epsilon;
  47045. this._vertexData[arrayOffset] = sprite.position.x;
  47046. this._vertexData[arrayOffset + 1] = sprite.position.y;
  47047. this._vertexData[arrayOffset + 2] = sprite.position.z;
  47048. this._vertexData[arrayOffset + 3] = sprite.angle;
  47049. this._vertexData[arrayOffset + 4] = sprite.width;
  47050. this._vertexData[arrayOffset + 5] = sprite.height;
  47051. this._vertexData[arrayOffset + 6] = offsetX;
  47052. this._vertexData[arrayOffset + 7] = offsetY;
  47053. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  47054. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  47055. var offset = (sprite.cellIndex / rowSize) >> 0;
  47056. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  47057. this._vertexData[arrayOffset + 11] = offset;
  47058. // Color
  47059. this._vertexData[arrayOffset + 12] = sprite.color.r;
  47060. this._vertexData[arrayOffset + 13] = sprite.color.g;
  47061. this._vertexData[arrayOffset + 14] = sprite.color.b;
  47062. this._vertexData[arrayOffset + 15] = sprite.color.a;
  47063. };
  47064. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  47065. var count = Math.min(this._capacity, this.sprites.length);
  47066. var min = BABYLON.Vector3.Zero();
  47067. var max = BABYLON.Vector3.Zero();
  47068. var distance = Number.MAX_VALUE;
  47069. var currentSprite = null;
  47070. var cameraSpacePosition = BABYLON.Vector3.Zero();
  47071. var cameraView = camera.getViewMatrix();
  47072. for (var index = 0; index < count; index++) {
  47073. var sprite = this.sprites[index];
  47074. if (!sprite) {
  47075. continue;
  47076. }
  47077. if (predicate) {
  47078. if (!predicate(sprite)) {
  47079. continue;
  47080. }
  47081. }
  47082. else if (!sprite.isPickable) {
  47083. continue;
  47084. }
  47085. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  47086. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  47087. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  47088. if (ray.intersectsBoxMinMax(min, max)) {
  47089. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  47090. if (distance > currentDistance) {
  47091. distance = currentDistance;
  47092. currentSprite = sprite;
  47093. if (fastCheck) {
  47094. break;
  47095. }
  47096. }
  47097. }
  47098. }
  47099. if (currentSprite) {
  47100. var result = new BABYLON.PickingInfo();
  47101. result.hit = true;
  47102. result.pickedSprite = currentSprite;
  47103. result.distance = distance;
  47104. return result;
  47105. }
  47106. return null;
  47107. };
  47108. SpriteManager.prototype.render = function () {
  47109. // Check
  47110. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  47111. return;
  47112. var engine = this._scene.getEngine();
  47113. var baseSize = this._spriteTexture.getBaseSize();
  47114. // Sprites
  47115. var deltaTime = engine.getDeltaTime();
  47116. var max = Math.min(this._capacity, this.sprites.length);
  47117. var rowSize = baseSize.width / this.cellWidth;
  47118. var offset = 0;
  47119. for (var index = 0; index < max; index++) {
  47120. var sprite = this.sprites[index];
  47121. if (!sprite) {
  47122. continue;
  47123. }
  47124. sprite._animate(deltaTime);
  47125. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  47126. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  47127. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  47128. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  47129. }
  47130. this._buffer.update(this._vertexData);
  47131. // Render
  47132. var effect = this._effectBase;
  47133. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  47134. effect = this._effectFog;
  47135. }
  47136. engine.enableEffect(effect);
  47137. var viewMatrix = this._scene.getViewMatrix();
  47138. effect.setTexture("diffuseSampler", this._spriteTexture);
  47139. effect.setMatrix("view", viewMatrix);
  47140. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47141. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  47142. // Fog
  47143. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  47144. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  47145. effect.setColor3("vFogColor", this._scene.fogColor);
  47146. }
  47147. // VBOs
  47148. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47149. // Draw order
  47150. engine.setDepthFunctionToLessOrEqual();
  47151. effect.setBool("alphaTest", true);
  47152. engine.setColorWrite(false);
  47153. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  47154. engine.setColorWrite(true);
  47155. effect.setBool("alphaTest", false);
  47156. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  47158. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47159. };
  47160. SpriteManager.prototype.dispose = function () {
  47161. if (this._buffer) {
  47162. this._buffer.dispose();
  47163. this._buffer = null;
  47164. }
  47165. if (this._indexBuffer) {
  47166. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47167. this._indexBuffer = null;
  47168. }
  47169. if (this._spriteTexture) {
  47170. this._spriteTexture.dispose();
  47171. this._spriteTexture = null;
  47172. }
  47173. // Remove from scene
  47174. var index = this._scene.spriteManagers.indexOf(this);
  47175. this._scene.spriteManagers.splice(index, 1);
  47176. // Callback
  47177. this.onDisposeObservable.notifyObservers(this);
  47178. this.onDisposeObservable.clear();
  47179. };
  47180. return SpriteManager;
  47181. }());
  47182. BABYLON.SpriteManager = SpriteManager;
  47183. })(BABYLON || (BABYLON = {}));
  47184. //# sourceMappingURL=babylon.spriteManager.js.map
  47185. var BABYLON;
  47186. (function (BABYLON) {
  47187. var Sprite = /** @class */ (function () {
  47188. function Sprite(name, manager) {
  47189. this.name = name;
  47190. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47191. this.width = 1.0;
  47192. this.height = 1.0;
  47193. this.angle = 0;
  47194. this.cellIndex = 0;
  47195. this.invertU = 0;
  47196. this.invertV = 0;
  47197. this.animations = new Array();
  47198. this.isPickable = false;
  47199. this._animationStarted = false;
  47200. this._loopAnimation = false;
  47201. this._fromIndex = 0;
  47202. this._toIndex = 0;
  47203. this._delay = 0;
  47204. this._direction = 1;
  47205. this._time = 0;
  47206. this._manager = manager;
  47207. this._manager.sprites.push(this);
  47208. this.position = BABYLON.Vector3.Zero();
  47209. }
  47210. Object.defineProperty(Sprite.prototype, "size", {
  47211. get: function () {
  47212. return this.width;
  47213. },
  47214. set: function (value) {
  47215. this.width = value;
  47216. this.height = value;
  47217. },
  47218. enumerable: true,
  47219. configurable: true
  47220. });
  47221. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  47222. this._fromIndex = from;
  47223. this._toIndex = to;
  47224. this._loopAnimation = loop;
  47225. this._delay = delay;
  47226. this._animationStarted = true;
  47227. this._direction = from < to ? 1 : -1;
  47228. this.cellIndex = from;
  47229. this._time = 0;
  47230. this._onAnimationEnd = onAnimationEnd;
  47231. };
  47232. Sprite.prototype.stopAnimation = function () {
  47233. this._animationStarted = false;
  47234. };
  47235. Sprite.prototype._animate = function (deltaTime) {
  47236. if (!this._animationStarted)
  47237. return;
  47238. this._time += deltaTime;
  47239. if (this._time > this._delay) {
  47240. this._time = this._time % this._delay;
  47241. this.cellIndex += this._direction;
  47242. if (this.cellIndex > this._toIndex) {
  47243. if (this._loopAnimation) {
  47244. this.cellIndex = this._fromIndex;
  47245. }
  47246. else {
  47247. this.cellIndex = this._toIndex;
  47248. this._animationStarted = false;
  47249. if (this._onAnimationEnd) {
  47250. this._onAnimationEnd();
  47251. }
  47252. if (this.disposeWhenFinishedAnimating) {
  47253. this.dispose();
  47254. }
  47255. }
  47256. }
  47257. }
  47258. };
  47259. Sprite.prototype.dispose = function () {
  47260. for (var i = 0; i < this._manager.sprites.length; i++) {
  47261. if (this._manager.sprites[i] == this) {
  47262. this._manager.sprites.splice(i, 1);
  47263. }
  47264. }
  47265. };
  47266. return Sprite;
  47267. }());
  47268. BABYLON.Sprite = Sprite;
  47269. })(BABYLON || (BABYLON = {}));
  47270. //# sourceMappingURL=babylon.sprite.js.map
  47271. var BABYLON;
  47272. (function (BABYLON) {
  47273. var IntersectionInfo = /** @class */ (function () {
  47274. function IntersectionInfo(bu, bv, distance) {
  47275. this.bu = bu;
  47276. this.bv = bv;
  47277. this.distance = distance;
  47278. this.faceId = 0;
  47279. this.subMeshId = 0;
  47280. }
  47281. return IntersectionInfo;
  47282. }());
  47283. BABYLON.IntersectionInfo = IntersectionInfo;
  47284. var PickingInfo = /** @class */ (function () {
  47285. function PickingInfo() {
  47286. this.hit = false;
  47287. this.distance = 0;
  47288. this.pickedPoint = null;
  47289. this.pickedMesh = null;
  47290. this.bu = 0;
  47291. this.bv = 0;
  47292. this.faceId = -1;
  47293. this.subMeshId = 0;
  47294. this.pickedSprite = null;
  47295. }
  47296. // Methods
  47297. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  47298. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  47299. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  47300. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  47301. return null;
  47302. }
  47303. var indices = this.pickedMesh.getIndices();
  47304. if (!indices) {
  47305. return null;
  47306. }
  47307. var result;
  47308. if (useVerticesNormals) {
  47309. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47310. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  47311. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  47312. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  47313. normal0 = normal0.scale(this.bu);
  47314. normal1 = normal1.scale(this.bv);
  47315. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  47316. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  47317. }
  47318. else {
  47319. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47320. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  47321. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  47322. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  47323. var p1p2 = vertex1.subtract(vertex2);
  47324. var p3p2 = vertex3.subtract(vertex2);
  47325. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  47326. }
  47327. if (useWorldCoordinates) {
  47328. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  47329. }
  47330. return BABYLON.Vector3.Normalize(result);
  47331. };
  47332. PickingInfo.prototype.getTextureCoordinates = function () {
  47333. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47334. return null;
  47335. }
  47336. var indices = this.pickedMesh.getIndices();
  47337. if (!indices) {
  47338. return null;
  47339. }
  47340. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47341. if (!uvs) {
  47342. return null;
  47343. }
  47344. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  47345. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  47346. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  47347. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  47348. uv1 = uv1.scale(this.bu);
  47349. uv2 = uv2.scale(this.bv);
  47350. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  47351. };
  47352. return PickingInfo;
  47353. }());
  47354. BABYLON.PickingInfo = PickingInfo;
  47355. })(BABYLON || (BABYLON = {}));
  47356. //# sourceMappingURL=babylon.pickingInfo.js.map
  47357. var BABYLON;
  47358. (function (BABYLON) {
  47359. var Ray = /** @class */ (function () {
  47360. function Ray(origin, direction, length) {
  47361. if (length === void 0) { length = Number.MAX_VALUE; }
  47362. this.origin = origin;
  47363. this.direction = direction;
  47364. this.length = length;
  47365. }
  47366. // Methods
  47367. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  47368. var d = 0.0;
  47369. var maxValue = Number.MAX_VALUE;
  47370. var inv;
  47371. var min;
  47372. var max;
  47373. var temp;
  47374. if (Math.abs(this.direction.x) < 0.0000001) {
  47375. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  47376. return false;
  47377. }
  47378. }
  47379. else {
  47380. inv = 1.0 / this.direction.x;
  47381. min = (minimum.x - this.origin.x) * inv;
  47382. max = (maximum.x - this.origin.x) * inv;
  47383. if (max === -Infinity) {
  47384. max = Infinity;
  47385. }
  47386. if (min > max) {
  47387. temp = min;
  47388. min = max;
  47389. max = temp;
  47390. }
  47391. d = Math.max(min, d);
  47392. maxValue = Math.min(max, maxValue);
  47393. if (d > maxValue) {
  47394. return false;
  47395. }
  47396. }
  47397. if (Math.abs(this.direction.y) < 0.0000001) {
  47398. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  47399. return false;
  47400. }
  47401. }
  47402. else {
  47403. inv = 1.0 / this.direction.y;
  47404. min = (minimum.y - this.origin.y) * inv;
  47405. max = (maximum.y - this.origin.y) * inv;
  47406. if (max === -Infinity) {
  47407. max = Infinity;
  47408. }
  47409. if (min > max) {
  47410. temp = min;
  47411. min = max;
  47412. max = temp;
  47413. }
  47414. d = Math.max(min, d);
  47415. maxValue = Math.min(max, maxValue);
  47416. if (d > maxValue) {
  47417. return false;
  47418. }
  47419. }
  47420. if (Math.abs(this.direction.z) < 0.0000001) {
  47421. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  47422. return false;
  47423. }
  47424. }
  47425. else {
  47426. inv = 1.0 / this.direction.z;
  47427. min = (minimum.z - this.origin.z) * inv;
  47428. max = (maximum.z - this.origin.z) * inv;
  47429. if (max === -Infinity) {
  47430. max = Infinity;
  47431. }
  47432. if (min > max) {
  47433. temp = min;
  47434. min = max;
  47435. max = temp;
  47436. }
  47437. d = Math.max(min, d);
  47438. maxValue = Math.min(max, maxValue);
  47439. if (d > maxValue) {
  47440. return false;
  47441. }
  47442. }
  47443. return true;
  47444. };
  47445. Ray.prototype.intersectsBox = function (box) {
  47446. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  47447. };
  47448. Ray.prototype.intersectsSphere = function (sphere) {
  47449. var x = sphere.center.x - this.origin.x;
  47450. var y = sphere.center.y - this.origin.y;
  47451. var z = sphere.center.z - this.origin.z;
  47452. var pyth = (x * x) + (y * y) + (z * z);
  47453. var rr = sphere.radius * sphere.radius;
  47454. if (pyth <= rr) {
  47455. return true;
  47456. }
  47457. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  47458. if (dot < 0.0) {
  47459. return false;
  47460. }
  47461. var temp = pyth - (dot * dot);
  47462. return temp <= rr;
  47463. };
  47464. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  47465. if (!this._edge1) {
  47466. this._edge1 = BABYLON.Vector3.Zero();
  47467. this._edge2 = BABYLON.Vector3.Zero();
  47468. this._pvec = BABYLON.Vector3.Zero();
  47469. this._tvec = BABYLON.Vector3.Zero();
  47470. this._qvec = BABYLON.Vector3.Zero();
  47471. }
  47472. vertex1.subtractToRef(vertex0, this._edge1);
  47473. vertex2.subtractToRef(vertex0, this._edge2);
  47474. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  47475. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  47476. if (det === 0) {
  47477. return null;
  47478. }
  47479. var invdet = 1 / det;
  47480. this.origin.subtractToRef(vertex0, this._tvec);
  47481. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  47482. if (bu < 0 || bu > 1.0) {
  47483. return null;
  47484. }
  47485. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  47486. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  47487. if (bv < 0 || bu + bv > 1.0) {
  47488. return null;
  47489. }
  47490. //check if the distance is longer than the predefined length.
  47491. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  47492. if (distance > this.length) {
  47493. return null;
  47494. }
  47495. return new BABYLON.IntersectionInfo(bu, bv, distance);
  47496. };
  47497. Ray.prototype.intersectsPlane = function (plane) {
  47498. var distance;
  47499. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  47500. if (Math.abs(result1) < 9.99999997475243E-07) {
  47501. return null;
  47502. }
  47503. else {
  47504. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  47505. distance = (-plane.d - result2) / result1;
  47506. if (distance < 0.0) {
  47507. if (distance < -9.99999997475243E-07) {
  47508. return null;
  47509. }
  47510. else {
  47511. return 0;
  47512. }
  47513. }
  47514. return distance;
  47515. }
  47516. };
  47517. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  47518. var tm = BABYLON.Tmp.Matrix[0];
  47519. mesh.getWorldMatrix().invertToRef(tm);
  47520. if (this._tmpRay) {
  47521. Ray.TransformToRef(this, tm, this._tmpRay);
  47522. }
  47523. else {
  47524. this._tmpRay = Ray.Transform(this, tm);
  47525. }
  47526. return mesh.intersects(this._tmpRay, fastCheck);
  47527. };
  47528. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  47529. if (results) {
  47530. results.length = 0;
  47531. }
  47532. else {
  47533. results = [];
  47534. }
  47535. for (var i = 0; i < meshes.length; i++) {
  47536. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  47537. if (pickInfo.hit) {
  47538. results.push(pickInfo);
  47539. }
  47540. }
  47541. results.sort(this._comparePickingInfo);
  47542. return results;
  47543. };
  47544. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  47545. if (pickingInfoA.distance < pickingInfoB.distance) {
  47546. return -1;
  47547. }
  47548. else if (pickingInfoA.distance > pickingInfoB.distance) {
  47549. return 1;
  47550. }
  47551. else {
  47552. return 0;
  47553. }
  47554. };
  47555. /**
  47556. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  47557. * @param sega the first point of the segment to test the intersection against
  47558. * @param segb the second point of the segment to test the intersection against
  47559. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  47560. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  47561. */
  47562. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  47563. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  47564. var u = segb.subtract(sega);
  47565. var v = rsegb.subtract(this.origin);
  47566. var w = sega.subtract(this.origin);
  47567. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  47568. var b = BABYLON.Vector3.Dot(u, v);
  47569. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  47570. var d = BABYLON.Vector3.Dot(u, w);
  47571. var e = BABYLON.Vector3.Dot(v, w);
  47572. var D = a * c - b * b; // always >= 0
  47573. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  47574. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  47575. // compute the line parameters of the two closest points
  47576. if (D < Ray.smallnum) {
  47577. sN = 0.0; // force using point P0 on segment S1
  47578. sD = 1.0; // to prevent possible division by 0.0 later
  47579. tN = e;
  47580. tD = c;
  47581. }
  47582. else {
  47583. sN = (b * e - c * d);
  47584. tN = (a * e - b * d);
  47585. if (sN < 0.0) {
  47586. sN = 0.0;
  47587. tN = e;
  47588. tD = c;
  47589. }
  47590. else if (sN > sD) {
  47591. sN = sD;
  47592. tN = e + b;
  47593. tD = c;
  47594. }
  47595. }
  47596. if (tN < 0.0) {
  47597. tN = 0.0;
  47598. // recompute sc for this edge
  47599. if (-d < 0.0) {
  47600. sN = 0.0;
  47601. }
  47602. else if (-d > a)
  47603. sN = sD;
  47604. else {
  47605. sN = -d;
  47606. sD = a;
  47607. }
  47608. }
  47609. else if (tN > tD) {
  47610. tN = tD;
  47611. // recompute sc for this edge
  47612. if ((-d + b) < 0.0) {
  47613. sN = 0;
  47614. }
  47615. else if ((-d + b) > a) {
  47616. sN = sD;
  47617. }
  47618. else {
  47619. sN = (-d + b);
  47620. sD = a;
  47621. }
  47622. }
  47623. // finally do the division to get sc and tc
  47624. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  47625. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  47626. // get the difference of the two closest points
  47627. var qtc = v.multiplyByFloats(tc, tc, tc);
  47628. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  47629. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  47630. if (isIntersected) {
  47631. return qtc.length();
  47632. }
  47633. return -1;
  47634. };
  47635. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47636. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  47637. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  47638. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  47639. this.direction.normalize();
  47640. return this;
  47641. };
  47642. // Statics
  47643. Ray.Zero = function () {
  47644. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  47645. };
  47646. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47647. var result = Ray.Zero();
  47648. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  47649. };
  47650. /**
  47651. * 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
  47652. * transformed to the given world matrix.
  47653. * @param origin The origin point
  47654. * @param end The end point
  47655. * @param world a matrix to transform the ray to. Default is the identity matrix.
  47656. */
  47657. Ray.CreateNewFromTo = function (origin, end, world) {
  47658. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  47659. var direction = end.subtract(origin);
  47660. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  47661. direction.normalize();
  47662. return Ray.Transform(new Ray(origin, direction, length), world);
  47663. };
  47664. Ray.Transform = function (ray, matrix) {
  47665. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  47666. Ray.TransformToRef(ray, matrix, result);
  47667. return result;
  47668. };
  47669. Ray.TransformToRef = function (ray, matrix, result) {
  47670. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  47671. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  47672. result.length = ray.length;
  47673. var dir = result.direction;
  47674. var len = dir.length();
  47675. if (!(len === 0 || len === 1)) {
  47676. var num = 1.0 / len;
  47677. dir.x *= num;
  47678. dir.y *= num;
  47679. dir.z *= num;
  47680. result.length *= len;
  47681. }
  47682. };
  47683. Ray.smallnum = 0.00000001;
  47684. Ray.rayl = 10e8;
  47685. return Ray;
  47686. }());
  47687. BABYLON.Ray = Ray;
  47688. })(BABYLON || (BABYLON = {}));
  47689. //# sourceMappingURL=babylon.ray.js.map
  47690. var BABYLON;
  47691. (function (BABYLON) {
  47692. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  47693. if (boxMin.x > sphereCenter.x + sphereRadius)
  47694. return false;
  47695. if (sphereCenter.x - sphereRadius > boxMax.x)
  47696. return false;
  47697. if (boxMin.y > sphereCenter.y + sphereRadius)
  47698. return false;
  47699. if (sphereCenter.y - sphereRadius > boxMax.y)
  47700. return false;
  47701. if (boxMin.z > sphereCenter.z + sphereRadius)
  47702. return false;
  47703. if (sphereCenter.z - sphereRadius > boxMax.z)
  47704. return false;
  47705. return true;
  47706. };
  47707. var getLowestRoot = (function () {
  47708. var result = { root: 0, found: false };
  47709. return function (a, b, c, maxR) {
  47710. result.root = 0;
  47711. result.found = false;
  47712. var determinant = b * b - 4.0 * a * c;
  47713. if (determinant < 0)
  47714. return result;
  47715. var sqrtD = Math.sqrt(determinant);
  47716. var r1 = (-b - sqrtD) / (2.0 * a);
  47717. var r2 = (-b + sqrtD) / (2.0 * a);
  47718. if (r1 > r2) {
  47719. var temp = r2;
  47720. r2 = r1;
  47721. r1 = temp;
  47722. }
  47723. if (r1 > 0 && r1 < maxR) {
  47724. result.root = r1;
  47725. result.found = true;
  47726. return result;
  47727. }
  47728. if (r2 > 0 && r2 < maxR) {
  47729. result.root = r2;
  47730. result.found = true;
  47731. return result;
  47732. }
  47733. return result;
  47734. };
  47735. })();
  47736. var Collider = /** @class */ (function () {
  47737. function Collider() {
  47738. this._collisionPoint = BABYLON.Vector3.Zero();
  47739. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47740. this._tempVector = BABYLON.Vector3.Zero();
  47741. this._tempVector2 = BABYLON.Vector3.Zero();
  47742. this._tempVector3 = BABYLON.Vector3.Zero();
  47743. this._tempVector4 = BABYLON.Vector3.Zero();
  47744. this._edge = BABYLON.Vector3.Zero();
  47745. this._baseToVertex = BABYLON.Vector3.Zero();
  47746. this._destinationPoint = BABYLON.Vector3.Zero();
  47747. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47748. this._displacementVector = BABYLON.Vector3.Zero();
  47749. this._radius = BABYLON.Vector3.One();
  47750. this._retry = 0;
  47751. this._basePointWorld = BABYLON.Vector3.Zero();
  47752. this._velocityWorld = BABYLON.Vector3.Zero();
  47753. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47754. this._collisionMask = -1;
  47755. }
  47756. Object.defineProperty(Collider.prototype, "collisionMask", {
  47757. get: function () {
  47758. return this._collisionMask;
  47759. },
  47760. set: function (mask) {
  47761. this._collisionMask = !isNaN(mask) ? mask : -1;
  47762. },
  47763. enumerable: true,
  47764. configurable: true
  47765. });
  47766. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47767. /**
  47768. * Gets the plane normal used to compute the sliding response (in local space)
  47769. */
  47770. get: function () {
  47771. return this._slidePlaneNormal;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. // Methods
  47777. Collider.prototype._initialize = function (source, dir, e) {
  47778. this._velocity = dir;
  47779. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47780. this._basePoint = source;
  47781. source.multiplyToRef(this._radius, this._basePointWorld);
  47782. dir.multiplyToRef(this._radius, this._velocityWorld);
  47783. this._velocityWorldLength = this._velocityWorld.length();
  47784. this._epsilon = e;
  47785. this.collisionFound = false;
  47786. };
  47787. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47788. pa.subtractToRef(point, this._tempVector);
  47789. pb.subtractToRef(point, this._tempVector2);
  47790. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47791. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47792. if (d < 0)
  47793. return false;
  47794. pc.subtractToRef(point, this._tempVector3);
  47795. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47796. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47797. if (d < 0)
  47798. return false;
  47799. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47800. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47801. return d >= 0;
  47802. };
  47803. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47804. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47805. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47806. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47807. return false;
  47808. }
  47809. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47810. return false;
  47811. return true;
  47812. };
  47813. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47814. var t0;
  47815. var embeddedInPlane = false;
  47816. //defensive programming, actually not needed.
  47817. if (!trianglePlaneArray) {
  47818. trianglePlaneArray = [];
  47819. }
  47820. if (!trianglePlaneArray[faceIndex]) {
  47821. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47822. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47823. }
  47824. var trianglePlane = trianglePlaneArray[faceIndex];
  47825. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47826. return;
  47827. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47828. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47829. if (normalDotVelocity == 0) {
  47830. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47831. return;
  47832. embeddedInPlane = true;
  47833. t0 = 0;
  47834. }
  47835. else {
  47836. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47837. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47838. if (t0 > t1) {
  47839. var temp = t1;
  47840. t1 = t0;
  47841. t0 = temp;
  47842. }
  47843. if (t0 > 1.0 || t1 < 0.0)
  47844. return;
  47845. if (t0 < 0)
  47846. t0 = 0;
  47847. if (t0 > 1.0)
  47848. t0 = 1.0;
  47849. }
  47850. this._collisionPoint.copyFromFloats(0, 0, 0);
  47851. var found = false;
  47852. var t = 1.0;
  47853. if (!embeddedInPlane) {
  47854. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47855. this._velocity.scaleToRef(t0, this._tempVector);
  47856. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47857. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47858. found = true;
  47859. t = t0;
  47860. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47861. }
  47862. }
  47863. if (!found) {
  47864. var velocitySquaredLength = this._velocity.lengthSquared();
  47865. var a = velocitySquaredLength;
  47866. this._basePoint.subtractToRef(p1, this._tempVector);
  47867. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47868. var c = this._tempVector.lengthSquared() - 1.0;
  47869. var lowestRoot = getLowestRoot(a, b, c, t);
  47870. if (lowestRoot.found) {
  47871. t = lowestRoot.root;
  47872. found = true;
  47873. this._collisionPoint.copyFrom(p1);
  47874. }
  47875. this._basePoint.subtractToRef(p2, this._tempVector);
  47876. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47877. c = this._tempVector.lengthSquared() - 1.0;
  47878. lowestRoot = getLowestRoot(a, b, c, t);
  47879. if (lowestRoot.found) {
  47880. t = lowestRoot.root;
  47881. found = true;
  47882. this._collisionPoint.copyFrom(p2);
  47883. }
  47884. this._basePoint.subtractToRef(p3, this._tempVector);
  47885. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47886. c = this._tempVector.lengthSquared() - 1.0;
  47887. lowestRoot = getLowestRoot(a, b, c, t);
  47888. if (lowestRoot.found) {
  47889. t = lowestRoot.root;
  47890. found = true;
  47891. this._collisionPoint.copyFrom(p3);
  47892. }
  47893. p2.subtractToRef(p1, this._edge);
  47894. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47895. var edgeSquaredLength = this._edge.lengthSquared();
  47896. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47897. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47898. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47899. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47900. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47901. lowestRoot = getLowestRoot(a, b, c, t);
  47902. if (lowestRoot.found) {
  47903. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47904. if (f >= 0.0 && f <= 1.0) {
  47905. t = lowestRoot.root;
  47906. found = true;
  47907. this._edge.scaleInPlace(f);
  47908. p1.addToRef(this._edge, this._collisionPoint);
  47909. }
  47910. }
  47911. p3.subtractToRef(p2, this._edge);
  47912. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47913. edgeSquaredLength = this._edge.lengthSquared();
  47914. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47915. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47916. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47917. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47918. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47919. lowestRoot = getLowestRoot(a, b, c, t);
  47920. if (lowestRoot.found) {
  47921. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47922. if (f >= 0.0 && f <= 1.0) {
  47923. t = lowestRoot.root;
  47924. found = true;
  47925. this._edge.scaleInPlace(f);
  47926. p2.addToRef(this._edge, this._collisionPoint);
  47927. }
  47928. }
  47929. p1.subtractToRef(p3, this._edge);
  47930. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47931. edgeSquaredLength = this._edge.lengthSquared();
  47932. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47933. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47934. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47935. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47936. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47937. lowestRoot = getLowestRoot(a, b, c, t);
  47938. if (lowestRoot.found) {
  47939. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47940. if (f >= 0.0 && f <= 1.0) {
  47941. t = lowestRoot.root;
  47942. found = true;
  47943. this._edge.scaleInPlace(f);
  47944. p3.addToRef(this._edge, this._collisionPoint);
  47945. }
  47946. }
  47947. }
  47948. if (found) {
  47949. var distToCollision = t * this._velocity.length();
  47950. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47951. if (!this.intersectionPoint) {
  47952. this.intersectionPoint = this._collisionPoint.clone();
  47953. }
  47954. else {
  47955. this.intersectionPoint.copyFrom(this._collisionPoint);
  47956. }
  47957. this._nearestDistance = distToCollision;
  47958. this.collisionFound = true;
  47959. }
  47960. }
  47961. };
  47962. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47963. for (var i = indexStart; i < indexEnd; i += 3) {
  47964. var p1 = pts[indices[i] - decal];
  47965. var p2 = pts[indices[i + 1] - decal];
  47966. var p3 = pts[indices[i + 2] - decal];
  47967. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47968. }
  47969. };
  47970. Collider.prototype._getResponse = function (pos, vel) {
  47971. pos.addToRef(vel, this._destinationPoint);
  47972. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47973. this._basePoint.addToRef(vel, pos);
  47974. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47975. this._slidePlaneNormal.normalize();
  47976. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47977. pos.addInPlace(this._displacementVector);
  47978. this.intersectionPoint.addInPlace(this._displacementVector);
  47979. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47980. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47981. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47982. };
  47983. return Collider;
  47984. }());
  47985. BABYLON.Collider = Collider;
  47986. })(BABYLON || (BABYLON = {}));
  47987. //# sourceMappingURL=babylon.collider.js.map
  47988. var BABYLON;
  47989. (function (BABYLON) {
  47990. //WebWorker code will be inserted to this variable.
  47991. BABYLON.CollisionWorker = "";
  47992. var WorkerTaskType;
  47993. (function (WorkerTaskType) {
  47994. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47995. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47996. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47997. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47998. var WorkerReplyType;
  47999. (function (WorkerReplyType) {
  48000. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  48001. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  48002. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  48003. var CollisionCoordinatorWorker = /** @class */ (function () {
  48004. function CollisionCoordinatorWorker() {
  48005. var _this = this;
  48006. this._scaledPosition = BABYLON.Vector3.Zero();
  48007. this._scaledVelocity = BABYLON.Vector3.Zero();
  48008. this.onMeshUpdated = function (transformNode) {
  48009. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  48010. };
  48011. this.onGeometryUpdated = function (geometry) {
  48012. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  48013. };
  48014. this._afterRender = function () {
  48015. if (!_this._init)
  48016. return;
  48017. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  48018. return;
  48019. }
  48020. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  48021. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  48022. if (_this._runningUpdated > 4) {
  48023. return;
  48024. }
  48025. ++_this._runningUpdated;
  48026. var payload = {
  48027. updatedMeshes: _this._addUpdateMeshesList,
  48028. updatedGeometries: _this._addUpdateGeometriesList,
  48029. removedGeometries: _this._toRemoveGeometryArray,
  48030. removedMeshes: _this._toRemoveMeshesArray
  48031. };
  48032. var message = {
  48033. payload: payload,
  48034. taskType: WorkerTaskType.UPDATE
  48035. };
  48036. var serializable = [];
  48037. for (var id in payload.updatedGeometries) {
  48038. if (payload.updatedGeometries.hasOwnProperty(id)) {
  48039. //prepare transferables
  48040. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  48041. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  48042. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  48043. }
  48044. }
  48045. _this._worker.postMessage(message, serializable);
  48046. _this._addUpdateMeshesList = {};
  48047. _this._addUpdateGeometriesList = {};
  48048. _this._toRemoveGeometryArray = [];
  48049. _this._toRemoveMeshesArray = [];
  48050. };
  48051. this._onMessageFromWorker = function (e) {
  48052. var returnData = e.data;
  48053. if (returnData.error != WorkerReplyType.SUCCESS) {
  48054. //TODO what errors can be returned from the worker?
  48055. BABYLON.Tools.Warn("error returned from worker!");
  48056. return;
  48057. }
  48058. switch (returnData.taskType) {
  48059. case WorkerTaskType.INIT:
  48060. _this._init = true;
  48061. //Update the worked with ALL of the scene's current state
  48062. _this._scene.meshes.forEach(function (mesh) {
  48063. _this.onMeshAdded(mesh);
  48064. });
  48065. _this._scene.getGeometries().forEach(function (geometry) {
  48066. _this.onGeometryAdded(geometry);
  48067. });
  48068. break;
  48069. case WorkerTaskType.UPDATE:
  48070. _this._runningUpdated--;
  48071. break;
  48072. case WorkerTaskType.COLLIDE:
  48073. var returnPayload = returnData.payload;
  48074. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  48075. return;
  48076. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  48077. if (callback) {
  48078. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  48079. if (mesh) {
  48080. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  48081. }
  48082. }
  48083. //cleanup
  48084. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  48085. break;
  48086. }
  48087. };
  48088. this._collisionsCallbackArray = [];
  48089. this._init = false;
  48090. this._runningUpdated = 0;
  48091. this._addUpdateMeshesList = {};
  48092. this._addUpdateGeometriesList = {};
  48093. this._toRemoveGeometryArray = [];
  48094. this._toRemoveMeshesArray = [];
  48095. }
  48096. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  48097. if (!this._init)
  48098. return;
  48099. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  48100. return;
  48101. position.divideToRef(collider._radius, this._scaledPosition);
  48102. displacement.divideToRef(collider._radius, this._scaledVelocity);
  48103. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  48104. var payload = {
  48105. collider: {
  48106. position: this._scaledPosition.asArray(),
  48107. velocity: this._scaledVelocity.asArray(),
  48108. radius: collider._radius.asArray()
  48109. },
  48110. collisionId: collisionIndex,
  48111. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  48112. maximumRetry: maximumRetry
  48113. };
  48114. var message = {
  48115. payload: payload,
  48116. taskType: WorkerTaskType.COLLIDE
  48117. };
  48118. this._worker.postMessage(message);
  48119. };
  48120. CollisionCoordinatorWorker.prototype.init = function (scene) {
  48121. this._scene = scene;
  48122. this._scene.registerAfterRender(this._afterRender);
  48123. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  48124. this._worker = new Worker(workerUrl);
  48125. this._worker.onmessage = this._onMessageFromWorker;
  48126. var message = {
  48127. payload: {},
  48128. taskType: WorkerTaskType.INIT
  48129. };
  48130. this._worker.postMessage(message);
  48131. };
  48132. CollisionCoordinatorWorker.prototype.destroy = function () {
  48133. this._scene.unregisterAfterRender(this._afterRender);
  48134. this._worker.terminate();
  48135. };
  48136. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  48137. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  48138. this.onMeshUpdated(mesh);
  48139. };
  48140. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  48141. this._toRemoveMeshesArray.push(mesh.uniqueId);
  48142. };
  48143. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  48144. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  48145. geometry.onGeometryUpdated = this.onGeometryUpdated;
  48146. this.onGeometryUpdated(geometry);
  48147. };
  48148. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  48149. this._toRemoveGeometryArray.push(geometry.id);
  48150. };
  48151. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  48152. var submeshes = [];
  48153. if (mesh.subMeshes) {
  48154. submeshes = mesh.subMeshes.map(function (sm, idx) {
  48155. var boundingInfo = sm.getBoundingInfo();
  48156. return {
  48157. position: idx,
  48158. verticesStart: sm.verticesStart,
  48159. verticesCount: sm.verticesCount,
  48160. indexStart: sm.indexStart,
  48161. indexCount: sm.indexCount,
  48162. hasMaterial: !!sm.getMaterial(),
  48163. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  48164. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  48165. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  48166. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  48167. };
  48168. });
  48169. }
  48170. var geometryId = null;
  48171. if (mesh instanceof BABYLON.Mesh) {
  48172. var geometry = mesh.geometry;
  48173. geometryId = geometry ? geometry.id : null;
  48174. }
  48175. else if (mesh instanceof BABYLON.InstancedMesh) {
  48176. var geometry = mesh.sourceMesh.geometry;
  48177. geometryId = geometry ? geometry.id : null;
  48178. }
  48179. var boundingInfo = mesh.getBoundingInfo();
  48180. return {
  48181. uniqueId: mesh.uniqueId,
  48182. id: mesh.id,
  48183. name: mesh.name,
  48184. geometryId: geometryId,
  48185. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  48186. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  48187. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  48188. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  48189. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  48190. subMeshes: submeshes,
  48191. checkCollisions: mesh.checkCollisions
  48192. };
  48193. };
  48194. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  48195. return {
  48196. id: geometry.id,
  48197. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  48198. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  48199. indices: new Uint32Array(geometry.getIndices() || []),
  48200. };
  48201. };
  48202. return CollisionCoordinatorWorker;
  48203. }());
  48204. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  48205. var CollisionCoordinatorLegacy = /** @class */ (function () {
  48206. function CollisionCoordinatorLegacy() {
  48207. this._scaledPosition = BABYLON.Vector3.Zero();
  48208. this._scaledVelocity = BABYLON.Vector3.Zero();
  48209. this._finalPosition = BABYLON.Vector3.Zero();
  48210. }
  48211. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  48212. position.divideToRef(collider._radius, this._scaledPosition);
  48213. displacement.divideToRef(collider._radius, this._scaledVelocity);
  48214. collider.collidedMesh = null;
  48215. collider._retry = 0;
  48216. collider._initialVelocity = this._scaledVelocity;
  48217. collider._initialPosition = this._scaledPosition;
  48218. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  48219. this._finalPosition.multiplyInPlace(collider._radius);
  48220. //run the callback
  48221. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  48222. };
  48223. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  48224. this._scene = scene;
  48225. };
  48226. CollisionCoordinatorLegacy.prototype.destroy = function () {
  48227. //Legacy need no destruction method.
  48228. };
  48229. //No update in legacy mode
  48230. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  48231. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  48232. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  48233. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  48234. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  48235. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  48236. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  48237. if (excludedMesh === void 0) { excludedMesh = null; }
  48238. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  48239. if (collider._retry >= maximumRetry) {
  48240. finalPosition.copyFrom(position);
  48241. return;
  48242. }
  48243. // Check if this is a mesh else camera or -1
  48244. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  48245. collider._initialize(position, velocity, closeDistance);
  48246. // Check all meshes
  48247. for (var index = 0; index < this._scene.meshes.length; index++) {
  48248. var mesh = this._scene.meshes[index];
  48249. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  48250. mesh._checkCollision(collider);
  48251. }
  48252. }
  48253. if (!collider.collisionFound) {
  48254. position.addToRef(velocity, finalPosition);
  48255. return;
  48256. }
  48257. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  48258. collider._getResponse(position, velocity);
  48259. }
  48260. if (velocity.length() <= closeDistance) {
  48261. finalPosition.copyFrom(position);
  48262. return;
  48263. }
  48264. collider._retry++;
  48265. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  48266. };
  48267. return CollisionCoordinatorLegacy;
  48268. }());
  48269. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  48270. })(BABYLON || (BABYLON = {}));
  48271. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  48272. var BABYLON;
  48273. (function (BABYLON) {
  48274. /**
  48275. * A particle represents one of the element emitted by a particle system.
  48276. * This is mainly define by its coordinates, direction, velocity and age.
  48277. */
  48278. var Particle = /** @class */ (function () {
  48279. /**
  48280. * Creates a new instance of @see Particle
  48281. * @param particleSystem the particle system the particle belongs to
  48282. */
  48283. function Particle(particleSystem) {
  48284. this.particleSystem = particleSystem;
  48285. /**
  48286. * The world position of the particle in the scene.
  48287. */
  48288. this.position = BABYLON.Vector3.Zero();
  48289. /**
  48290. * The world direction of the particle in the scene.
  48291. */
  48292. this.direction = BABYLON.Vector3.Zero();
  48293. /**
  48294. * The color of the particle.
  48295. */
  48296. this.color = new BABYLON.Color4(0, 0, 0, 0);
  48297. /**
  48298. * The color change of the particle per step.
  48299. */
  48300. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  48301. /**
  48302. * Defines how long will the life of the particle be.
  48303. */
  48304. this.lifeTime = 1.0;
  48305. /**
  48306. * The current age of the particle.
  48307. */
  48308. this.age = 0;
  48309. /**
  48310. * The current size of the particle.
  48311. */
  48312. this.size = 0;
  48313. /**
  48314. * The current angle of the particle.
  48315. */
  48316. this.angle = 0;
  48317. /**
  48318. * Defines how fast is the angle changing.
  48319. */
  48320. this.angularSpeed = 0;
  48321. /**
  48322. * Defines the cell index used by the particle to be rendered from a sprite.
  48323. */
  48324. this.cellIndex = 0;
  48325. this._currentFrameCounter = 0;
  48326. if (!this.particleSystem.isAnimationSheetEnabled) {
  48327. return;
  48328. }
  48329. this.cellIndex = this.particleSystem.startSpriteCellID;
  48330. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  48331. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  48332. }
  48333. else {
  48334. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  48335. }
  48336. }
  48337. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  48338. // (ageOffset / scaledUpdateSpeed) / available cells
  48339. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  48340. this._currentFrameCounter += scaledUpdateSpeed;
  48341. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  48342. this._currentFrameCounter = 0;
  48343. this.cellIndex++;
  48344. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48345. this.cellIndex = this.particleSystem.endSpriteCellID;
  48346. }
  48347. }
  48348. };
  48349. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  48350. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  48351. this.cellIndex++;
  48352. this._currentFrameCounter = 0;
  48353. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48354. if (this.particleSystem.spriteCellLoop) {
  48355. this.cellIndex = this.particleSystem.startSpriteCellID;
  48356. }
  48357. else {
  48358. this.cellIndex = this.particleSystem.endSpriteCellID;
  48359. }
  48360. }
  48361. }
  48362. else {
  48363. this._currentFrameCounter++;
  48364. }
  48365. };
  48366. /**
  48367. * Copy the properties of particle to another one.
  48368. * @param other the particle to copy the information to.
  48369. */
  48370. Particle.prototype.copyTo = function (other) {
  48371. other.position.copyFrom(this.position);
  48372. other.direction.copyFrom(this.direction);
  48373. other.color.copyFrom(this.color);
  48374. other.colorStep.copyFrom(this.colorStep);
  48375. other.lifeTime = this.lifeTime;
  48376. other.age = this.age;
  48377. other.size = this.size;
  48378. other.angle = this.angle;
  48379. other.angularSpeed = this.angularSpeed;
  48380. other.particleSystem = this.particleSystem;
  48381. other.cellIndex = this.cellIndex;
  48382. };
  48383. return Particle;
  48384. }());
  48385. BABYLON.Particle = Particle;
  48386. })(BABYLON || (BABYLON = {}));
  48387. //# sourceMappingURL=babylon.particle.js.map
  48388. var BABYLON;
  48389. (function (BABYLON) {
  48390. /**
  48391. * This represents a particle system in Babylon.
  48392. * 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.
  48393. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  48394. * @example https://doc.babylonjs.com/babylon101/particles
  48395. */
  48396. var ParticleSystem = /** @class */ (function () {
  48397. /**
  48398. * Instantiates a particle system.
  48399. * 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.
  48400. * @param name The name of the particle system
  48401. * @param capacity The max number of particles alive at the same time
  48402. * @param scene The scene the particle system belongs to
  48403. * @param customEffect a custom effect used to change the way particles are rendered by default
  48404. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  48405. * @param epsilon Offset used to render the particles
  48406. */
  48407. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  48408. if (customEffect === void 0) { customEffect = null; }
  48409. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  48410. if (epsilon === void 0) { epsilon = 0.01; }
  48411. var _this = this;
  48412. /**
  48413. * List of animations used by the particle system.
  48414. */
  48415. this.animations = [];
  48416. /**
  48417. * The rendering group used by the Particle system to chose when to render.
  48418. */
  48419. this.renderingGroupId = 0;
  48420. /**
  48421. * The emitter represents the Mesh or position we are attaching the particle system to.
  48422. */
  48423. this.emitter = null;
  48424. /**
  48425. * The density of particles, the rate of particle flow
  48426. */
  48427. this.emitRate = 10;
  48428. /**
  48429. * If you want to launch only a few particles at once, that can be done, as well.
  48430. */
  48431. this.manualEmitCount = -1;
  48432. /**
  48433. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  48434. */
  48435. this.updateSpeed = 0.01;
  48436. /**
  48437. * The amount of time the particle system is running (depends of the overall speed above).
  48438. */
  48439. this.targetStopDuration = 0;
  48440. /**
  48441. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  48442. */
  48443. this.disposeOnStop = false;
  48444. /**
  48445. * Minimum power of emitting particles.
  48446. */
  48447. this.minEmitPower = 1;
  48448. /**
  48449. * Maximum power of emitting particles.
  48450. */
  48451. this.maxEmitPower = 1;
  48452. /**
  48453. * Minimum life time of emitting particles.
  48454. */
  48455. this.minLifeTime = 1;
  48456. /**
  48457. * Maximum life time of emitting particles.
  48458. */
  48459. this.maxLifeTime = 1;
  48460. /**
  48461. * Minimum Size of emitting particles.
  48462. */
  48463. this.minSize = 1;
  48464. /**
  48465. * Maximum Size of emitting particles.
  48466. */
  48467. this.maxSize = 1;
  48468. /**
  48469. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  48470. */
  48471. this.minAngularSpeed = 0;
  48472. /**
  48473. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  48474. */
  48475. this.maxAngularSpeed = 0;
  48476. /**
  48477. * The layer mask we are rendering the particles through.
  48478. */
  48479. this.layerMask = 0x0FFFFFFF;
  48480. /**
  48481. * This can help using your own shader to render the particle system.
  48482. * The according effect will be created
  48483. */
  48484. this.customShader = null;
  48485. /**
  48486. * By default particle system starts as soon as they are created. This prevents the
  48487. * automatic start to happen and let you decide when to start emitting particles.
  48488. */
  48489. this.preventAutoStart = false;
  48490. /**
  48491. * Callback triggered when the particle animation is ending.
  48492. */
  48493. this.onAnimationEnd = null;
  48494. /**
  48495. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  48496. */
  48497. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  48498. /**
  48499. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  48500. * to override the particles.
  48501. */
  48502. this.forceDepthWrite = false;
  48503. /**
  48504. * You can use gravity if you want to give an orientation to your particles.
  48505. */
  48506. this.gravity = BABYLON.Vector3.Zero();
  48507. /**
  48508. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48509. */
  48510. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  48511. /**
  48512. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48513. */
  48514. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  48515. /**
  48516. * 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.
  48517. */
  48518. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  48519. /**
  48520. * 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.
  48521. */
  48522. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48523. /**
  48524. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48525. */
  48526. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48527. /**
  48528. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48529. */
  48530. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48531. /**
  48532. * Color the particle will have at the end of its lifetime.
  48533. */
  48534. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  48535. /**
  48536. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  48537. */
  48538. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48539. /**
  48540. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  48541. */
  48542. this.spriteCellLoop = true;
  48543. /**
  48544. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  48545. */
  48546. this.spriteCellChangeSpeed = 0;
  48547. /**
  48548. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  48549. */
  48550. this.startSpriteCellID = 0;
  48551. /**
  48552. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  48553. */
  48554. this.endSpriteCellID = 0;
  48555. /**
  48556. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  48557. */
  48558. this.spriteCellWidth = 0;
  48559. /**
  48560. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  48561. */
  48562. this.spriteCellHeight = 0;
  48563. /**
  48564. * An event triggered when the system is disposed.
  48565. */
  48566. this.onDisposeObservable = new BABYLON.Observable();
  48567. this._particles = new Array();
  48568. this._stockParticles = new Array();
  48569. this._newPartsExcess = 0;
  48570. this._vertexBuffers = {};
  48571. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  48572. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48573. this._scaledDirection = BABYLON.Vector3.Zero();
  48574. this._scaledGravity = BABYLON.Vector3.Zero();
  48575. this._currentRenderId = -1;
  48576. this._started = false;
  48577. this._stopped = false;
  48578. this._actualFrame = 0;
  48579. this._vertexBufferSize = 11;
  48580. this._appendParticleVertexes = null;
  48581. this.id = name;
  48582. this.name = name;
  48583. this._capacity = capacity;
  48584. this._epsilon = epsilon;
  48585. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  48586. if (isAnimationSheetEnabled) {
  48587. this._vertexBufferSize = 12;
  48588. }
  48589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48590. this._customEffect = customEffect;
  48591. scene.particleSystems.push(this);
  48592. this._createIndexBuffer();
  48593. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  48594. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  48595. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  48596. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  48597. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  48598. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  48599. if (this._isAnimationSheetEnabled) {
  48600. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  48601. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  48602. }
  48603. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48604. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48605. this._vertexBuffers["options"] = options;
  48606. // Default behaviors
  48607. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  48608. this.updateFunction = function (particles) {
  48609. for (var index = 0; index < particles.length; index++) {
  48610. var particle = particles[index];
  48611. particle.age += _this._scaledUpdateSpeed;
  48612. if (particle.age >= particle.lifeTime) {
  48613. _this.recycleParticle(particle);
  48614. index--;
  48615. continue;
  48616. }
  48617. else {
  48618. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  48619. particle.color.addInPlace(_this._scaledColorStep);
  48620. if (particle.color.a < 0)
  48621. particle.color.a = 0;
  48622. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  48623. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  48624. particle.position.addInPlace(_this._scaledDirection);
  48625. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  48626. particle.direction.addInPlace(_this._scaledGravity);
  48627. if (_this._isAnimationSheetEnabled) {
  48628. particle.updateCellIndex(_this._scaledUpdateSpeed);
  48629. }
  48630. }
  48631. }
  48632. };
  48633. }
  48634. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  48635. /**
  48636. * Sets a callback that will be triggered when the system is disposed.
  48637. */
  48638. set: function (callback) {
  48639. if (this._onDisposeObserver) {
  48640. this.onDisposeObservable.remove(this._onDisposeObserver);
  48641. }
  48642. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48643. },
  48644. enumerable: true,
  48645. configurable: true
  48646. });
  48647. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  48648. /**
  48649. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  48650. */
  48651. get: function () {
  48652. return this._isAnimationSheetEnabled;
  48653. },
  48654. enumerable: true,
  48655. configurable: true
  48656. });
  48657. ParticleSystem.prototype._createIndexBuffer = function () {
  48658. var indices = [];
  48659. var index = 0;
  48660. for (var count = 0; count < this._capacity; count++) {
  48661. indices.push(index);
  48662. indices.push(index + 1);
  48663. indices.push(index + 2);
  48664. indices.push(index);
  48665. indices.push(index + 2);
  48666. indices.push(index + 3);
  48667. index += 4;
  48668. }
  48669. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  48670. };
  48671. /**
  48672. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  48673. * Its lifetime will start back at 0.
  48674. * @param particle The particle to recycle
  48675. */
  48676. ParticleSystem.prototype.recycleParticle = function (particle) {
  48677. var lastParticle = this._particles.pop();
  48678. if (lastParticle !== particle) {
  48679. lastParticle.copyTo(particle);
  48680. this._stockParticles.push(lastParticle);
  48681. }
  48682. };
  48683. /**
  48684. * Gets the maximum number of particles active at the same time.
  48685. * @returns The max number of active particles.
  48686. */
  48687. ParticleSystem.prototype.getCapacity = function () {
  48688. return this._capacity;
  48689. };
  48690. /**
  48691. * Gets Wether there are still active particles in the system.
  48692. * @returns True if it is alive, otherwise false.
  48693. */
  48694. ParticleSystem.prototype.isAlive = function () {
  48695. return this._alive;
  48696. };
  48697. /**
  48698. * Gets Wether the system has been started.
  48699. * @returns True if it has been started, otherwise false.
  48700. */
  48701. ParticleSystem.prototype.isStarted = function () {
  48702. return this._started;
  48703. };
  48704. /**
  48705. * Starts the particle system and begins to emit.
  48706. */
  48707. ParticleSystem.prototype.start = function () {
  48708. this._started = true;
  48709. this._stopped = false;
  48710. this._actualFrame = 0;
  48711. };
  48712. /**
  48713. * Stops the particle system.
  48714. */
  48715. ParticleSystem.prototype.stop = function () {
  48716. this._stopped = true;
  48717. };
  48718. /**
  48719. * @ignore (for internal use only)
  48720. */
  48721. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  48722. var offset = index * this._vertexBufferSize;
  48723. this._vertexData[offset] = particle.position.x;
  48724. this._vertexData[offset + 1] = particle.position.y;
  48725. this._vertexData[offset + 2] = particle.position.z;
  48726. this._vertexData[offset + 3] = particle.color.r;
  48727. this._vertexData[offset + 4] = particle.color.g;
  48728. this._vertexData[offset + 5] = particle.color.b;
  48729. this._vertexData[offset + 6] = particle.color.a;
  48730. this._vertexData[offset + 7] = particle.angle;
  48731. this._vertexData[offset + 8] = particle.size;
  48732. this._vertexData[offset + 9] = offsetX;
  48733. this._vertexData[offset + 10] = offsetY;
  48734. };
  48735. /**
  48736. * @ignore (for internal use only)
  48737. */
  48738. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48739. if (offsetX === 0)
  48740. offsetX = this._epsilon;
  48741. else if (offsetX === 1)
  48742. offsetX = 1 - this._epsilon;
  48743. if (offsetY === 0)
  48744. offsetY = this._epsilon;
  48745. else if (offsetY === 1)
  48746. offsetY = 1 - this._epsilon;
  48747. var offset = index * this._vertexBufferSize;
  48748. this._vertexData[offset] = particle.position.x;
  48749. this._vertexData[offset + 1] = particle.position.y;
  48750. this._vertexData[offset + 2] = particle.position.z;
  48751. this._vertexData[offset + 3] = particle.color.r;
  48752. this._vertexData[offset + 4] = particle.color.g;
  48753. this._vertexData[offset + 5] = particle.color.b;
  48754. this._vertexData[offset + 6] = particle.color.a;
  48755. this._vertexData[offset + 7] = particle.angle;
  48756. this._vertexData[offset + 8] = particle.size;
  48757. this._vertexData[offset + 9] = offsetX;
  48758. this._vertexData[offset + 10] = offsetY;
  48759. this._vertexData[offset + 11] = particle.cellIndex;
  48760. };
  48761. ParticleSystem.prototype._update = function (newParticles) {
  48762. // Update current
  48763. this._alive = this._particles.length > 0;
  48764. this.updateFunction(this._particles);
  48765. // Add new ones
  48766. var worldMatrix;
  48767. if (this.emitter.position) {
  48768. var emitterMesh = this.emitter;
  48769. worldMatrix = emitterMesh.getWorldMatrix();
  48770. }
  48771. else {
  48772. var emitterPosition = this.emitter;
  48773. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48774. }
  48775. var particle;
  48776. for (var index = 0; index < newParticles; index++) {
  48777. if (this._particles.length === this._capacity) {
  48778. break;
  48779. }
  48780. if (this._stockParticles.length !== 0) {
  48781. particle = this._stockParticles.pop();
  48782. particle.age = 0;
  48783. particle.cellIndex = this.startSpriteCellID;
  48784. }
  48785. else {
  48786. particle = new BABYLON.Particle(this);
  48787. }
  48788. this._particles.push(particle);
  48789. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48790. if (this.startPositionFunction) {
  48791. this.startPositionFunction(worldMatrix, particle.position, particle);
  48792. }
  48793. else {
  48794. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48795. }
  48796. if (this.startDirectionFunction) {
  48797. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48798. }
  48799. else {
  48800. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48801. }
  48802. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48803. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48804. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48805. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48806. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48807. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48808. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48809. }
  48810. };
  48811. ParticleSystem.prototype._getEffect = function () {
  48812. if (this._customEffect) {
  48813. return this._customEffect;
  48814. }
  48815. ;
  48816. var defines = [];
  48817. if (this._scene.clipPlane) {
  48818. defines.push("#define CLIPPLANE");
  48819. }
  48820. if (this._isAnimationSheetEnabled) {
  48821. defines.push("#define ANIMATESHEET");
  48822. }
  48823. // Effect
  48824. var join = defines.join("\n");
  48825. if (this._cachedDefines !== join) {
  48826. this._cachedDefines = join;
  48827. var attributesNamesOrOptions;
  48828. var effectCreationOption;
  48829. if (this._isAnimationSheetEnabled) {
  48830. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48831. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48832. }
  48833. else {
  48834. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48835. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48836. }
  48837. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48838. }
  48839. return this._effect;
  48840. };
  48841. /**
  48842. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48843. */
  48844. ParticleSystem.prototype.animate = function () {
  48845. if (!this._started)
  48846. return;
  48847. var effect = this._getEffect();
  48848. // Check
  48849. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48850. return;
  48851. if (this._currentRenderId === this._scene.getRenderId()) {
  48852. return;
  48853. }
  48854. this._currentRenderId = this._scene.getRenderId();
  48855. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48856. // determine the number of particles we need to create
  48857. var newParticles;
  48858. if (this.manualEmitCount > -1) {
  48859. newParticles = this.manualEmitCount;
  48860. this._newPartsExcess = 0;
  48861. this.manualEmitCount = 0;
  48862. }
  48863. else {
  48864. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48865. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48866. }
  48867. if (this._newPartsExcess > 1.0) {
  48868. newParticles += this._newPartsExcess >> 0;
  48869. this._newPartsExcess -= this._newPartsExcess >> 0;
  48870. }
  48871. this._alive = false;
  48872. if (!this._stopped) {
  48873. this._actualFrame += this._scaledUpdateSpeed;
  48874. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48875. this.stop();
  48876. }
  48877. else {
  48878. newParticles = 0;
  48879. }
  48880. this._update(newParticles);
  48881. // Stopped?
  48882. if (this._stopped) {
  48883. if (!this._alive) {
  48884. this._started = false;
  48885. if (this.onAnimationEnd) {
  48886. this.onAnimationEnd();
  48887. }
  48888. if (this.disposeOnStop) {
  48889. this._scene._toBeDisposed.push(this);
  48890. }
  48891. }
  48892. }
  48893. // Animation sheet
  48894. if (this._isAnimationSheetEnabled) {
  48895. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48896. }
  48897. else {
  48898. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48899. }
  48900. // Update VBO
  48901. var offset = 0;
  48902. for (var index = 0; index < this._particles.length; index++) {
  48903. var particle = this._particles[index];
  48904. this._appendParticleVertexes(offset, particle);
  48905. offset += 4;
  48906. }
  48907. if (this._vertexBuffer) {
  48908. this._vertexBuffer.update(this._vertexData);
  48909. }
  48910. };
  48911. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48912. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48913. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48914. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48915. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48916. };
  48917. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48918. this._appendParticleVertex(offset++, particle, 0, 0);
  48919. this._appendParticleVertex(offset++, particle, 1, 0);
  48920. this._appendParticleVertex(offset++, particle, 1, 1);
  48921. this._appendParticleVertex(offset++, particle, 0, 1);
  48922. };
  48923. /**
  48924. * Rebuilds the particle system.
  48925. */
  48926. ParticleSystem.prototype.rebuild = function () {
  48927. this._createIndexBuffer();
  48928. if (this._vertexBuffer) {
  48929. this._vertexBuffer._rebuild();
  48930. }
  48931. };
  48932. /**
  48933. * Renders the particle system in its current state.
  48934. * @returns the current number of particles.
  48935. */
  48936. ParticleSystem.prototype.render = function () {
  48937. var effect = this._getEffect();
  48938. // Check
  48939. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48940. return 0;
  48941. var engine = this._scene.getEngine();
  48942. // Render
  48943. engine.enableEffect(effect);
  48944. engine.setState(false);
  48945. var viewMatrix = this._scene.getViewMatrix();
  48946. effect.setTexture("diffuseSampler", this.particleTexture);
  48947. effect.setMatrix("view", viewMatrix);
  48948. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48949. if (this._isAnimationSheetEnabled) {
  48950. var baseSize = this.particleTexture.getBaseSize();
  48951. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48952. }
  48953. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48954. if (this._scene.clipPlane) {
  48955. var clipPlane = this._scene.clipPlane;
  48956. var invView = viewMatrix.clone();
  48957. invView.invert();
  48958. effect.setMatrix("invView", invView);
  48959. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48960. }
  48961. // VBOs
  48962. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48963. // Draw order
  48964. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48965. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48966. }
  48967. else {
  48968. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48969. }
  48970. if (this.forceDepthWrite) {
  48971. engine.setDepthWrite(true);
  48972. }
  48973. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48974. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48975. return this._particles.length;
  48976. };
  48977. /**
  48978. * Disposes the particle system and free the associated resources.
  48979. */
  48980. ParticleSystem.prototype.dispose = function () {
  48981. if (this._vertexBuffer) {
  48982. this._vertexBuffer.dispose();
  48983. this._vertexBuffer = null;
  48984. }
  48985. if (this._indexBuffer) {
  48986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48987. this._indexBuffer = null;
  48988. }
  48989. if (this.particleTexture) {
  48990. this.particleTexture.dispose();
  48991. this.particleTexture = null;
  48992. }
  48993. // Remove from scene
  48994. var index = this._scene.particleSystems.indexOf(this);
  48995. if (index > -1) {
  48996. this._scene.particleSystems.splice(index, 1);
  48997. }
  48998. // Callback
  48999. this.onDisposeObservable.notifyObservers(this);
  49000. this.onDisposeObservable.clear();
  49001. };
  49002. /**
  49003. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  49004. * @param radius The radius of the sphere to emit from
  49005. * @returns the emitter
  49006. */
  49007. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  49008. if (radius === void 0) { radius = 1; }
  49009. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  49010. this.particleEmitterType = particleEmitter;
  49011. return particleEmitter;
  49012. };
  49013. /**
  49014. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  49015. * @param radius The radius of the sphere to emit from
  49016. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  49017. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  49018. * @returns the emitter
  49019. */
  49020. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  49021. if (radius === void 0) { radius = 1; }
  49022. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  49023. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  49024. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  49025. this.particleEmitterType = particleEmitter;
  49026. return particleEmitter;
  49027. };
  49028. /**
  49029. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  49030. * @param radius The radius of the cone to emit from
  49031. * @param angle The base angle of the cone
  49032. * @returns the emitter
  49033. */
  49034. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  49035. if (radius === void 0) { radius = 1; }
  49036. if (angle === void 0) { angle = Math.PI / 4; }
  49037. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  49038. this.particleEmitterType = particleEmitter;
  49039. return particleEmitter;
  49040. };
  49041. // 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.
  49042. /**
  49043. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  49044. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  49045. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  49046. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  49047. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  49048. * @returns the emitter
  49049. */
  49050. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  49051. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  49052. this.direction1 = direction1;
  49053. this.direction2 = direction2;
  49054. this.minEmitBox = minEmitBox;
  49055. this.maxEmitBox = maxEmitBox;
  49056. this.particleEmitterType = particleEmitter;
  49057. return particleEmitter;
  49058. };
  49059. /**
  49060. * Clones the particle system.
  49061. * @param name The name of the cloned object
  49062. * @param newEmitter The new emitter to use
  49063. * @returns the cloned particle system
  49064. */
  49065. ParticleSystem.prototype.clone = function (name, newEmitter) {
  49066. var custom = null;
  49067. var program = null;
  49068. if (this.customShader != null) {
  49069. program = this.customShader;
  49070. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  49071. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  49072. }
  49073. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  49074. result.customShader = program;
  49075. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  49076. if (newEmitter === undefined) {
  49077. newEmitter = this.emitter;
  49078. }
  49079. result.emitter = newEmitter;
  49080. if (this.particleTexture) {
  49081. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  49082. }
  49083. if (!this.preventAutoStart) {
  49084. result.start();
  49085. }
  49086. return result;
  49087. };
  49088. /**
  49089. * Serializes the particle system to a JSON object.
  49090. * @returns the JSON object
  49091. */
  49092. ParticleSystem.prototype.serialize = function () {
  49093. var serializationObject = {};
  49094. serializationObject.name = this.name;
  49095. serializationObject.id = this.id;
  49096. // Emitter
  49097. if (this.emitter.position) {
  49098. var emitterMesh = this.emitter;
  49099. serializationObject.emitterId = emitterMesh.id;
  49100. }
  49101. else {
  49102. var emitterPosition = this.emitter;
  49103. serializationObject.emitter = emitterPosition.asArray();
  49104. }
  49105. serializationObject.capacity = this.getCapacity();
  49106. if (this.particleTexture) {
  49107. serializationObject.textureName = this.particleTexture.name;
  49108. }
  49109. // Animations
  49110. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  49111. // Particle system
  49112. serializationObject.minAngularSpeed = this.minAngularSpeed;
  49113. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  49114. serializationObject.minSize = this.minSize;
  49115. serializationObject.maxSize = this.maxSize;
  49116. serializationObject.minEmitPower = this.minEmitPower;
  49117. serializationObject.maxEmitPower = this.maxEmitPower;
  49118. serializationObject.minLifeTime = this.minLifeTime;
  49119. serializationObject.maxLifeTime = this.maxLifeTime;
  49120. serializationObject.emitRate = this.emitRate;
  49121. serializationObject.minEmitBox = this.minEmitBox.asArray();
  49122. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  49123. serializationObject.gravity = this.gravity.asArray();
  49124. serializationObject.direction1 = this.direction1.asArray();
  49125. serializationObject.direction2 = this.direction2.asArray();
  49126. serializationObject.color1 = this.color1.asArray();
  49127. serializationObject.color2 = this.color2.asArray();
  49128. serializationObject.colorDead = this.colorDead.asArray();
  49129. serializationObject.updateSpeed = this.updateSpeed;
  49130. serializationObject.targetStopDuration = this.targetStopDuration;
  49131. serializationObject.textureMask = this.textureMask.asArray();
  49132. serializationObject.blendMode = this.blendMode;
  49133. serializationObject.customShader = this.customShader;
  49134. serializationObject.preventAutoStart = this.preventAutoStart;
  49135. serializationObject.startSpriteCellID = this.startSpriteCellID;
  49136. serializationObject.endSpriteCellID = this.endSpriteCellID;
  49137. serializationObject.spriteCellLoop = this.spriteCellLoop;
  49138. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  49139. serializationObject.spriteCellWidth = this.spriteCellWidth;
  49140. serializationObject.spriteCellHeight = this.spriteCellHeight;
  49141. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  49142. return serializationObject;
  49143. };
  49144. /**
  49145. * Parses a JSON object to create a particle system.
  49146. * @param parsedParticleSystem The JSON object to parse
  49147. * @param scene The scene to create the particle system in
  49148. * @param rootUrl The root url to use to load external dependencies like texture
  49149. * @returns the Parsed particle system
  49150. */
  49151. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  49152. var name = parsedParticleSystem.name;
  49153. var custom = null;
  49154. var program = null;
  49155. if (parsedParticleSystem.customShader) {
  49156. program = parsedParticleSystem.customShader;
  49157. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  49158. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  49159. }
  49160. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  49161. particleSystem.customShader = program;
  49162. if (parsedParticleSystem.id) {
  49163. particleSystem.id = parsedParticleSystem.id;
  49164. }
  49165. // Auto start
  49166. if (parsedParticleSystem.preventAutoStart) {
  49167. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  49168. }
  49169. // Texture
  49170. if (parsedParticleSystem.textureName) {
  49171. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  49172. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  49173. }
  49174. // Emitter
  49175. if (parsedParticleSystem.emitterId) {
  49176. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  49177. }
  49178. else {
  49179. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  49180. }
  49181. // Animations
  49182. if (parsedParticleSystem.animations) {
  49183. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  49184. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  49185. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49186. }
  49187. }
  49188. if (parsedParticleSystem.autoAnimate) {
  49189. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  49190. }
  49191. // Particle system
  49192. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  49193. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  49194. particleSystem.minSize = parsedParticleSystem.minSize;
  49195. particleSystem.maxSize = parsedParticleSystem.maxSize;
  49196. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  49197. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  49198. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  49199. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  49200. particleSystem.emitRate = parsedParticleSystem.emitRate;
  49201. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  49202. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  49203. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  49204. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  49205. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  49206. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  49207. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  49208. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  49209. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  49210. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  49211. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  49212. particleSystem.blendMode = parsedParticleSystem.blendMode;
  49213. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  49214. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  49215. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  49216. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  49217. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  49218. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  49219. if (!particleSystem.preventAutoStart) {
  49220. particleSystem.start();
  49221. }
  49222. return particleSystem;
  49223. };
  49224. /**
  49225. * Source color is added to the destination color without alpha affecting the result.
  49226. */
  49227. ParticleSystem.BLENDMODE_ONEONE = 0;
  49228. /**
  49229. * Blend current color and particle color using particle’s alpha.
  49230. */
  49231. ParticleSystem.BLENDMODE_STANDARD = 1;
  49232. return ParticleSystem;
  49233. }());
  49234. BABYLON.ParticleSystem = ParticleSystem;
  49235. })(BABYLON || (BABYLON = {}));
  49236. //# sourceMappingURL=babylon.particleSystem.js.map
  49237. var BABYLON;
  49238. (function (BABYLON) {
  49239. /**
  49240. * Particle emitter emitting particles from the inside of a box.
  49241. * It emits the particles randomly between 2 given directions.
  49242. */
  49243. var BoxParticleEmitter = /** @class */ (function () {
  49244. // to be updated like the rest of emitters when breaking changes.
  49245. // all property should be come public variables and passed through constructor.
  49246. /**
  49247. * Creates a new instance of @see BoxParticleEmitter
  49248. * @param _particleSystem the particle system associated with the emitter
  49249. */
  49250. function BoxParticleEmitter(_particleSystem) {
  49251. this._particleSystem = _particleSystem;
  49252. }
  49253. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  49254. /**
  49255. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49256. */
  49257. get: function () {
  49258. return this._particleSystem.direction1;
  49259. },
  49260. /**
  49261. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49262. */
  49263. set: function (value) {
  49264. this._particleSystem.direction1 = value;
  49265. },
  49266. enumerable: true,
  49267. configurable: true
  49268. });
  49269. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  49270. /**
  49271. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49272. */
  49273. get: function () {
  49274. return this._particleSystem.direction2;
  49275. },
  49276. /**
  49277. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49278. */
  49279. set: function (value) {
  49280. this._particleSystem.direction2 = value;
  49281. },
  49282. enumerable: true,
  49283. configurable: true
  49284. });
  49285. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  49286. /**
  49287. * 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.
  49288. */
  49289. get: function () {
  49290. return this._particleSystem.minEmitBox;
  49291. },
  49292. /**
  49293. * 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.
  49294. */
  49295. set: function (value) {
  49296. this._particleSystem.minEmitBox = value;
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  49302. /**
  49303. * 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.
  49304. */
  49305. get: function () {
  49306. return this._particleSystem.maxEmitBox;
  49307. },
  49308. /**
  49309. * 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.
  49310. */
  49311. set: function (value) {
  49312. this._particleSystem.maxEmitBox = value;
  49313. },
  49314. enumerable: true,
  49315. configurable: true
  49316. });
  49317. /**
  49318. * Called by the particle System when the direction is computed for the created particle.
  49319. * @param emitPower is the power of the particle (speed)
  49320. * @param worldMatrix is the world matrix of the particle system
  49321. * @param directionToUpdate is the direction vector to update with the result
  49322. * @param particle is the particle we are computed the direction for
  49323. */
  49324. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49325. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49326. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49327. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49328. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49329. };
  49330. /**
  49331. * Called by the particle System when the position is computed for the created particle.
  49332. * @param worldMatrix is the world matrix of the particle system
  49333. * @param positionToUpdate is the position vector to update with the result
  49334. * @param particle is the particle we are computed the position for
  49335. */
  49336. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49337. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  49338. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  49339. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  49340. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49341. };
  49342. /**
  49343. * Clones the current emitter and returns a copy of it
  49344. * @returns the new emitter
  49345. */
  49346. BoxParticleEmitter.prototype.clone = function () {
  49347. var newOne = new BoxParticleEmitter(this._particleSystem);
  49348. BABYLON.Tools.DeepCopy(this, newOne);
  49349. return newOne;
  49350. };
  49351. return BoxParticleEmitter;
  49352. }());
  49353. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  49354. })(BABYLON || (BABYLON = {}));
  49355. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  49356. var BABYLON;
  49357. (function (BABYLON) {
  49358. /**
  49359. * Particle emitter emitting particles from the inside of a cone.
  49360. * It emits the particles alongside the cone volume from the base to the particle.
  49361. * The emission direction might be randomized.
  49362. */
  49363. var ConeParticleEmitter = /** @class */ (function () {
  49364. /**
  49365. * Creates a new instance of @see ConeParticleEmitter
  49366. * @param radius the radius of the emission cone
  49367. * @param angles the cone base angle
  49368. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49369. */
  49370. function ConeParticleEmitter(radius,
  49371. /**
  49372. * The radius of the emission cone.
  49373. */
  49374. angle,
  49375. /**
  49376. * The cone base angle.
  49377. */
  49378. directionRandomizer) {
  49379. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49380. this.angle = angle;
  49381. this.directionRandomizer = directionRandomizer;
  49382. this.radius = radius;
  49383. }
  49384. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  49385. /**
  49386. * Gets the radius of the emission cone.
  49387. */
  49388. get: function () {
  49389. return this._radius;
  49390. },
  49391. /**
  49392. * Sets the radius of the emission cone.
  49393. */
  49394. set: function (value) {
  49395. this._radius = value;
  49396. if (this.angle !== 0) {
  49397. this._height = value / Math.tan(this.angle / 2);
  49398. }
  49399. else {
  49400. this._height = 1;
  49401. }
  49402. },
  49403. enumerable: true,
  49404. configurable: true
  49405. });
  49406. /**
  49407. * Called by the particle System when the direction is computed for the created particle.
  49408. * @param emitPower is the power of the particle (speed)
  49409. * @param worldMatrix is the world matrix of the particle system
  49410. * @param directionToUpdate is the direction vector to update with the result
  49411. * @param particle is the particle we are computed the direction for
  49412. */
  49413. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49414. if (this.angle === 0) {
  49415. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  49416. }
  49417. else {
  49418. // measure the direction Vector from the emitter to the particle.
  49419. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49420. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49421. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49422. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49423. direction.x += randX;
  49424. direction.y += randY;
  49425. direction.z += randZ;
  49426. direction.normalize();
  49427. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49428. }
  49429. };
  49430. /**
  49431. * Called by the particle System when the position is computed for the created particle.
  49432. * @param worldMatrix is the world matrix of the particle system
  49433. * @param positionToUpdate is the position vector to update with the result
  49434. * @param particle is the particle we are computed the position for
  49435. */
  49436. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49437. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  49438. var h = BABYLON.Scalar.RandomRange(0, 1);
  49439. // Better distribution in a cone at normal angles.
  49440. h = 1 - h * h;
  49441. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  49442. radius = radius * h / this._height;
  49443. var randX = radius * Math.sin(s);
  49444. var randZ = radius * Math.cos(s);
  49445. var randY = h;
  49446. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49447. };
  49448. /**
  49449. * Clones the current emitter and returns a copy of it
  49450. * @returns the new emitter
  49451. */
  49452. ConeParticleEmitter.prototype.clone = function () {
  49453. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  49454. BABYLON.Tools.DeepCopy(this, newOne);
  49455. return newOne;
  49456. };
  49457. return ConeParticleEmitter;
  49458. }());
  49459. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  49460. })(BABYLON || (BABYLON = {}));
  49461. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  49462. var BABYLON;
  49463. (function (BABYLON) {
  49464. /**
  49465. * Particle emitter emitting particles from the inside of a sphere.
  49466. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  49467. */
  49468. var SphereParticleEmitter = /** @class */ (function () {
  49469. /**
  49470. * Creates a new instance of @see SphereParticleEmitter
  49471. * @param radius the radius of the emission sphere
  49472. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49473. */
  49474. function SphereParticleEmitter(
  49475. /**
  49476. * The radius of the emission sphere.
  49477. */
  49478. radius,
  49479. /**
  49480. * How much to randomize the particle direction [0-1].
  49481. */
  49482. directionRandomizer) {
  49483. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49484. this.radius = radius;
  49485. this.directionRandomizer = directionRandomizer;
  49486. }
  49487. /**
  49488. * Called by the particle System when the direction is computed for the created particle.
  49489. * @param emitPower is the power of the particle (speed)
  49490. * @param worldMatrix is the world matrix of the particle system
  49491. * @param directionToUpdate is the direction vector to update with the result
  49492. * @param particle is the particle we are computed the direction for
  49493. */
  49494. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49495. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49496. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49497. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49498. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49499. direction.x += randX;
  49500. direction.y += randY;
  49501. direction.z += randZ;
  49502. direction.normalize();
  49503. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49504. };
  49505. /**
  49506. * Called by the particle System when the position is computed for the created particle.
  49507. * @param worldMatrix is the world matrix of the particle system
  49508. * @param positionToUpdate is the position vector to update with the result
  49509. * @param particle is the particle we are computed the position for
  49510. */
  49511. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49512. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  49513. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  49514. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  49515. var randY = this.radius * Math.cos(theta);
  49516. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  49517. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49518. };
  49519. /**
  49520. * Clones the current emitter and returns a copy of it
  49521. * @returns the new emitter
  49522. */
  49523. SphereParticleEmitter.prototype.clone = function () {
  49524. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  49525. BABYLON.Tools.DeepCopy(this, newOne);
  49526. return newOne;
  49527. };
  49528. return SphereParticleEmitter;
  49529. }());
  49530. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  49531. /**
  49532. * Particle emitter emitting particles from the inside of a sphere.
  49533. * It emits the particles randomly between two vectors.
  49534. */
  49535. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  49536. __extends(SphereDirectedParticleEmitter, _super);
  49537. /**
  49538. * Creates a new instance of @see SphereDirectedParticleEmitter
  49539. * @param radius the radius of the emission sphere
  49540. * @param direction1 the min limit of the emission direction
  49541. * @param direction2 the max limit of the emission direction
  49542. */
  49543. function SphereDirectedParticleEmitter(radius,
  49544. /**
  49545. * The min limit of the emission direction.
  49546. */
  49547. direction1,
  49548. /**
  49549. * The max limit of the emission direction.
  49550. */
  49551. direction2) {
  49552. var _this = _super.call(this, radius) || this;
  49553. _this.direction1 = direction1;
  49554. _this.direction2 = direction2;
  49555. return _this;
  49556. }
  49557. /**
  49558. * Called by the particle System when the direction is computed for the created particle.
  49559. * @param emitPower is the power of the particle (speed)
  49560. * @param worldMatrix is the world matrix of the particle system
  49561. * @param directionToUpdate is the direction vector to update with the result
  49562. * @param particle is the particle we are computed the direction for
  49563. */
  49564. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49565. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49566. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49567. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49568. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49569. };
  49570. /**
  49571. * Clones the current emitter and returns a copy of it
  49572. * @returns the new emitter
  49573. */
  49574. SphereDirectedParticleEmitter.prototype.clone = function () {
  49575. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  49576. BABYLON.Tools.DeepCopy(this, newOne);
  49577. return newOne;
  49578. };
  49579. return SphereDirectedParticleEmitter;
  49580. }(SphereParticleEmitter));
  49581. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  49582. })(BABYLON || (BABYLON = {}));
  49583. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  49584. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  49585. var BABYLON;
  49586. (function (BABYLON) {
  49587. /**
  49588. * Represents one particle of a solid particle system.
  49589. * @see SolidParticleSystem
  49590. */
  49591. var SolidParticle = /** @class */ (function () {
  49592. /**
  49593. * Creates a Solid Particle object.
  49594. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49595. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49596. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49597. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49598. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49599. * @param shapeId (integer) is the model shape identifier in the SPS.
  49600. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49601. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49602. */
  49603. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49604. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49605. /**
  49606. * particle global index
  49607. */
  49608. this.idx = 0;
  49609. /**
  49610. * The color of the particle
  49611. */
  49612. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49613. /**
  49614. * The world space position of the particle.
  49615. */
  49616. this.position = BABYLON.Vector3.Zero();
  49617. /**
  49618. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49619. */
  49620. this.rotation = BABYLON.Vector3.Zero();
  49621. /**
  49622. * The scaling of the particle.
  49623. */
  49624. this.scaling = BABYLON.Vector3.One();
  49625. /**
  49626. * The uvs of the particle.
  49627. */
  49628. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49629. /**
  49630. * The current speed of the particle.
  49631. */
  49632. this.velocity = BABYLON.Vector3.Zero();
  49633. /**
  49634. * The pivot point in the particle local space.
  49635. */
  49636. this.pivot = BABYLON.Vector3.Zero();
  49637. /**
  49638. * Is the particle active or not ?
  49639. */
  49640. this.alive = true;
  49641. /**
  49642. * Is the particle visible or not ?
  49643. */
  49644. this.isVisible = true;
  49645. /**
  49646. * Index of this particle in the global "positions" array (Internal use)
  49647. */
  49648. this._pos = 0;
  49649. /**
  49650. * Index of this particle in the global "indices" array (Internal use)
  49651. */
  49652. this._ind = 0;
  49653. /**
  49654. * ModelShape id of this particle
  49655. */
  49656. this.shapeId = 0;
  49657. /**
  49658. * Index of the particle in its shape id (Internal use)
  49659. */
  49660. this.idxInShape = 0;
  49661. /**
  49662. * Still set as invisible in order to skip useless computations (Internal use)
  49663. */
  49664. this._stillInvisible = false;
  49665. /**
  49666. * Last computed particle rotation matrix
  49667. */
  49668. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  49669. this.idx = particleIndex;
  49670. this._pos = positionIndex;
  49671. this._ind = indiceIndex;
  49672. this._model = model;
  49673. this.shapeId = shapeId;
  49674. this.idxInShape = idxInShape;
  49675. this._sps = sps;
  49676. if (modelBoundingInfo) {
  49677. this._modelBoundingInfo = modelBoundingInfo;
  49678. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49679. }
  49680. }
  49681. Object.defineProperty(SolidParticle.prototype, "scale", {
  49682. /**
  49683. * Legacy support, changed scale to scaling
  49684. */
  49685. get: function () {
  49686. return this.scaling;
  49687. },
  49688. /**
  49689. * Legacy support, changed scale to scaling
  49690. */
  49691. set: function (scale) {
  49692. this.scaling = scale;
  49693. },
  49694. enumerable: true,
  49695. configurable: true
  49696. });
  49697. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49698. /**
  49699. * Legacy support, changed quaternion to rotationQuaternion
  49700. */
  49701. get: function () {
  49702. return this.rotationQuaternion;
  49703. },
  49704. /**
  49705. * Legacy support, changed quaternion to rotationQuaternion
  49706. */
  49707. set: function (q) {
  49708. this.rotationQuaternion = q;
  49709. },
  49710. enumerable: true,
  49711. configurable: true
  49712. });
  49713. /**
  49714. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49715. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49716. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49717. * @returns true if it intersects
  49718. */
  49719. SolidParticle.prototype.intersectsMesh = function (target) {
  49720. if (!this._boundingInfo || !target._boundingInfo) {
  49721. return false;
  49722. }
  49723. if (this._sps._bSphereOnly) {
  49724. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49725. }
  49726. return this._boundingInfo.intersects(target._boundingInfo, false);
  49727. };
  49728. return SolidParticle;
  49729. }());
  49730. BABYLON.SolidParticle = SolidParticle;
  49731. /**
  49732. * Represents the shape of the model used by one particle of a solid particle system.
  49733. * SPS internal tool, don't use it manually.
  49734. * @see SolidParticleSystem
  49735. */
  49736. var ModelShape = /** @class */ (function () {
  49737. /**
  49738. * 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.
  49739. * SPS internal tool, don't use it manually.
  49740. * @ignore
  49741. */
  49742. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49743. /**
  49744. * length of the shape in the model indices array (internal use)
  49745. */
  49746. this._indicesLength = 0;
  49747. this.shapeID = id;
  49748. this._shape = shape;
  49749. this._indicesLength = indicesLength;
  49750. this._shapeUV = shapeUV;
  49751. this._positionFunction = posFunction;
  49752. this._vertexFunction = vtxFunction;
  49753. }
  49754. return ModelShape;
  49755. }());
  49756. BABYLON.ModelShape = ModelShape;
  49757. /**
  49758. * Represents a Depth Sorted Particle in the solid particle system.
  49759. * @see SolidParticleSystem
  49760. */
  49761. var DepthSortedParticle = /** @class */ (function () {
  49762. function DepthSortedParticle() {
  49763. /**
  49764. * Index of the particle in the "indices" array
  49765. */
  49766. this.ind = 0;
  49767. /**
  49768. * Length of the particle shape in the "indices" array
  49769. */
  49770. this.indicesLength = 0;
  49771. /**
  49772. * Squared distance from the particle to the camera
  49773. */
  49774. this.sqDistance = 0.0;
  49775. }
  49776. return DepthSortedParticle;
  49777. }());
  49778. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49779. })(BABYLON || (BABYLON = {}));
  49780. //# sourceMappingURL=babylon.solidParticle.js.map
  49781. var BABYLON;
  49782. (function (BABYLON) {
  49783. /**
  49784. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49785. *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.
  49786. * The SPS is also a particle system. It provides some methods to manage the particles.
  49787. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49788. *
  49789. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49790. */
  49791. var SolidParticleSystem = /** @class */ (function () {
  49792. /**
  49793. * Creates a SPS (Solid Particle System) object.
  49794. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49795. * @param scene (Scene) is the scene in which the SPS is added.
  49796. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49797. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49798. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49799. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49800. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49801. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49802. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49803. */
  49804. function SolidParticleSystem(name, scene, options) {
  49805. /**
  49806. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49807. * Example : var p = SPS.particles[i];
  49808. */
  49809. this.particles = new Array();
  49810. /**
  49811. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49812. */
  49813. this.nbParticles = 0;
  49814. /**
  49815. * If the particles must ever face the camera (default false). Useful for planar particles.
  49816. */
  49817. this.billboard = false;
  49818. /**
  49819. * Recompute normals when adding a shape
  49820. */
  49821. this.recomputeNormals = true;
  49822. /**
  49823. * This a counter ofr your own usage. It's not set by any SPS functions.
  49824. */
  49825. this.counter = 0;
  49826. /**
  49827. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49828. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49829. */
  49830. this.vars = {};
  49831. /**
  49832. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49833. */
  49834. this._bSphereOnly = false;
  49835. /**
  49836. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49837. */
  49838. this._bSphereRadiusFactor = 1.0;
  49839. this._positions = new Array();
  49840. this._indices = new Array();
  49841. this._normals = new Array();
  49842. this._colors = new Array();
  49843. this._uvs = new Array();
  49844. this._index = 0; // indices index
  49845. this._updatable = true;
  49846. this._pickable = false;
  49847. this._isVisibilityBoxLocked = false;
  49848. this._alwaysVisible = false;
  49849. this._depthSort = false;
  49850. this._shapeCounter = 0;
  49851. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49852. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49853. this._computeParticleColor = true;
  49854. this._computeParticleTexture = true;
  49855. this._computeParticleRotation = true;
  49856. this._computeParticleVertex = false;
  49857. this._computeBoundingBox = false;
  49858. this._depthSortParticles = true;
  49859. this._cam_axisZ = BABYLON.Vector3.Zero();
  49860. this._cam_axisY = BABYLON.Vector3.Zero();
  49861. this._cam_axisX = BABYLON.Vector3.Zero();
  49862. this._axisZ = BABYLON.Axis.Z;
  49863. this._camDir = BABYLON.Vector3.Zero();
  49864. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49865. this._rotMatrix = new BABYLON.Matrix();
  49866. this._invertMatrix = new BABYLON.Matrix();
  49867. this._rotated = BABYLON.Vector3.Zero();
  49868. this._quaternion = new BABYLON.Quaternion();
  49869. this._vertex = BABYLON.Vector3.Zero();
  49870. this._normal = BABYLON.Vector3.Zero();
  49871. this._yaw = 0.0;
  49872. this._pitch = 0.0;
  49873. this._roll = 0.0;
  49874. this._halfroll = 0.0;
  49875. this._halfpitch = 0.0;
  49876. this._halfyaw = 0.0;
  49877. this._sinRoll = 0.0;
  49878. this._cosRoll = 0.0;
  49879. this._sinPitch = 0.0;
  49880. this._cosPitch = 0.0;
  49881. this._sinYaw = 0.0;
  49882. this._cosYaw = 0.0;
  49883. this._mustUnrotateFixedNormals = false;
  49884. this._minimum = BABYLON.Tmp.Vector3[0];
  49885. this._maximum = BABYLON.Tmp.Vector3[1];
  49886. this._minBbox = BABYLON.Tmp.Vector3[4];
  49887. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49888. this._particlesIntersect = false;
  49889. this._depthSortFunction = function (p1, p2) {
  49890. return (p2.sqDistance - p1.sqDistance);
  49891. };
  49892. this._needs32Bits = false;
  49893. this.name = name;
  49894. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49895. this._camera = scene.activeCamera;
  49896. this._pickable = options ? options.isPickable : false;
  49897. this._depthSort = options ? options.enableDepthSort : false;
  49898. this._particlesIntersect = options ? options.particleIntersection : false;
  49899. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49900. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49901. if (options && options.updatable) {
  49902. this._updatable = options.updatable;
  49903. }
  49904. else {
  49905. this._updatable = true;
  49906. }
  49907. if (this._pickable) {
  49908. this.pickedParticles = [];
  49909. }
  49910. if (this._depthSort) {
  49911. this.depthSortedParticles = [];
  49912. }
  49913. }
  49914. /**
  49915. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49916. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49917. * @returns the created mesh
  49918. */
  49919. SolidParticleSystem.prototype.buildMesh = function () {
  49920. if (this.nbParticles === 0) {
  49921. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49922. this.addShape(triangle, 1);
  49923. triangle.dispose();
  49924. }
  49925. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49926. this._positions32 = new Float32Array(this._positions);
  49927. this._uvs32 = new Float32Array(this._uvs);
  49928. this._colors32 = new Float32Array(this._colors);
  49929. if (this.recomputeNormals) {
  49930. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49931. }
  49932. this._normals32 = new Float32Array(this._normals);
  49933. this._fixedNormal32 = new Float32Array(this._normals);
  49934. if (this._mustUnrotateFixedNormals) {
  49935. this._unrotateFixedNormals();
  49936. }
  49937. var vertexData = new BABYLON.VertexData();
  49938. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49939. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49940. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49941. if (this._uvs32) {
  49942. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49943. ;
  49944. }
  49945. if (this._colors32) {
  49946. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49947. }
  49948. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49949. vertexData.applyToMesh(mesh, this._updatable);
  49950. this.mesh = mesh;
  49951. this.mesh.isPickable = this._pickable;
  49952. // free memory
  49953. if (!this._depthSort) {
  49954. this._indices = null;
  49955. }
  49956. this._positions = null;
  49957. this._normals = null;
  49958. this._uvs = null;
  49959. this._colors = null;
  49960. if (!this._updatable) {
  49961. this.particles.length = 0;
  49962. }
  49963. return mesh;
  49964. };
  49965. /**
  49966. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49967. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49968. * Thus the particles generated from `digest()` have their property `position` set yet.
  49969. * @param mesh ( Mesh ) is the mesh to be digested
  49970. * @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
  49971. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49972. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49973. * @returns the current SPS
  49974. */
  49975. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49976. var size = (options && options.facetNb) || 1;
  49977. var number = (options && options.number) || 0;
  49978. var delta = (options && options.delta) || 0;
  49979. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49980. var meshInd = mesh.getIndices();
  49981. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49982. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49983. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49984. var f = 0; // facet counter
  49985. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49986. // compute size from number
  49987. if (number) {
  49988. number = (number > totalFacets) ? totalFacets : number;
  49989. size = Math.round(totalFacets / number);
  49990. delta = 0;
  49991. }
  49992. else {
  49993. size = (size > totalFacets) ? totalFacets : size;
  49994. }
  49995. var facetPos = []; // submesh positions
  49996. var facetInd = []; // submesh indices
  49997. var facetUV = []; // submesh UV
  49998. var facetCol = []; // submesh colors
  49999. var barycenter = BABYLON.Tmp.Vector3[0];
  50000. var sizeO = size;
  50001. while (f < totalFacets) {
  50002. size = sizeO + Math.floor((1 + delta) * Math.random());
  50003. if (f > totalFacets - size) {
  50004. size = totalFacets - f;
  50005. }
  50006. // reset temp arrays
  50007. facetPos.length = 0;
  50008. facetInd.length = 0;
  50009. facetUV.length = 0;
  50010. facetCol.length = 0;
  50011. // iterate over "size" facets
  50012. var fi = 0;
  50013. for (var j = f * 3; j < (f + size) * 3; j++) {
  50014. facetInd.push(fi);
  50015. var i = meshInd[j];
  50016. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  50017. if (meshUV) {
  50018. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  50019. }
  50020. if (meshCol) {
  50021. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  50022. }
  50023. fi++;
  50024. }
  50025. // create a model shape for each single particle
  50026. var idx = this.nbParticles;
  50027. var shape = this._posToShape(facetPos);
  50028. var shapeUV = this._uvsToShapeUV(facetUV);
  50029. // compute the barycenter of the shape
  50030. var v;
  50031. for (v = 0; v < shape.length; v++) {
  50032. barycenter.addInPlace(shape[v]);
  50033. }
  50034. barycenter.scaleInPlace(1 / shape.length);
  50035. // shift the shape from its barycenter to the origin
  50036. for (v = 0; v < shape.length; v++) {
  50037. shape[v].subtractInPlace(barycenter);
  50038. }
  50039. var bInfo;
  50040. if (this._particlesIntersect) {
  50041. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  50042. }
  50043. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  50044. // add the particle in the SPS
  50045. var currentPos = this._positions.length;
  50046. var currentInd = this._indices.length;
  50047. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  50048. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  50049. // initialize the particle position
  50050. this.particles[this.nbParticles].position.addInPlace(barycenter);
  50051. this._index += shape.length;
  50052. idx++;
  50053. this.nbParticles++;
  50054. this._shapeCounter++;
  50055. f += size;
  50056. }
  50057. return this;
  50058. };
  50059. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  50060. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  50061. var index = 0;
  50062. var idx = 0;
  50063. for (var p = 0; p < this.particles.length; p++) {
  50064. this._particle = this.particles[p];
  50065. this._shape = this._particle._model._shape;
  50066. if (this._particle.rotationQuaternion) {
  50067. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50068. }
  50069. else {
  50070. this._yaw = this._particle.rotation.y;
  50071. this._pitch = this._particle.rotation.x;
  50072. this._roll = this._particle.rotation.z;
  50073. this._quaternionRotationYPR();
  50074. }
  50075. this._quaternionToRotationMatrix();
  50076. this._rotMatrix.invertToRef(this._invertMatrix);
  50077. for (var pt = 0; pt < this._shape.length; pt++) {
  50078. idx = index + pt * 3;
  50079. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  50080. this._fixedNormal32[idx] = this._normal.x;
  50081. this._fixedNormal32[idx + 1] = this._normal.y;
  50082. this._fixedNormal32[idx + 2] = this._normal.z;
  50083. }
  50084. index = idx + 3;
  50085. }
  50086. };
  50087. //reset copy
  50088. SolidParticleSystem.prototype._resetCopy = function () {
  50089. this._copy.position.x = 0;
  50090. this._copy.position.y = 0;
  50091. this._copy.position.z = 0;
  50092. this._copy.rotation.x = 0;
  50093. this._copy.rotation.y = 0;
  50094. this._copy.rotation.z = 0;
  50095. this._copy.rotationQuaternion = null;
  50096. this._copy.scaling.x = 1.0;
  50097. this._copy.scaling.y = 1.0;
  50098. this._copy.scaling.z = 1.0;
  50099. this._copy.uvs.x = 0;
  50100. this._copy.uvs.y = 0;
  50101. this._copy.uvs.z = 1.0;
  50102. this._copy.uvs.w = 1.0;
  50103. this._copy.color = null;
  50104. };
  50105. // _meshBuilder : inserts the shape model in the global SPS mesh
  50106. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  50107. var i;
  50108. var u = 0;
  50109. var c = 0;
  50110. var n = 0;
  50111. this._resetCopy();
  50112. if (options && options.positionFunction) {
  50113. options.positionFunction(this._copy, idx, idxInShape);
  50114. this._mustUnrotateFixedNormals = true;
  50115. }
  50116. if (this._copy.rotationQuaternion) {
  50117. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50118. }
  50119. else {
  50120. this._yaw = this._copy.rotation.y;
  50121. this._pitch = this._copy.rotation.x;
  50122. this._roll = this._copy.rotation.z;
  50123. this._quaternionRotationYPR();
  50124. }
  50125. this._quaternionToRotationMatrix();
  50126. for (i = 0; i < shape.length; i++) {
  50127. this._vertex.x = shape[i].x;
  50128. this._vertex.y = shape[i].y;
  50129. this._vertex.z = shape[i].z;
  50130. if (options && options.vertexFunction) {
  50131. options.vertexFunction(this._copy, this._vertex, i);
  50132. }
  50133. this._vertex.x *= this._copy.scaling.x;
  50134. this._vertex.y *= this._copy.scaling.y;
  50135. this._vertex.z *= this._copy.scaling.z;
  50136. this._vertex.x += this._copy.pivot.x;
  50137. this._vertex.y += this._copy.pivot.y;
  50138. this._vertex.z += this._copy.pivot.z;
  50139. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50140. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50141. if (meshUV) {
  50142. 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);
  50143. u += 2;
  50144. }
  50145. if (this._copy.color) {
  50146. this._color = this._copy.color;
  50147. }
  50148. else if (meshCol && meshCol[c] !== undefined) {
  50149. this._color.r = meshCol[c];
  50150. this._color.g = meshCol[c + 1];
  50151. this._color.b = meshCol[c + 2];
  50152. this._color.a = meshCol[c + 3];
  50153. }
  50154. else {
  50155. this._color.r = 1.0;
  50156. this._color.g = 1.0;
  50157. this._color.b = 1.0;
  50158. this._color.a = 1.0;
  50159. }
  50160. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50161. c += 4;
  50162. if (!this.recomputeNormals && meshNor) {
  50163. this._normal.x = meshNor[n];
  50164. this._normal.y = meshNor[n + 1];
  50165. this._normal.z = meshNor[n + 2];
  50166. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  50167. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50168. n += 3;
  50169. }
  50170. }
  50171. for (i = 0; i < meshInd.length; i++) {
  50172. var current_ind = p + meshInd[i];
  50173. indices.push(current_ind);
  50174. if (current_ind > 65535) {
  50175. this._needs32Bits = true;
  50176. }
  50177. }
  50178. if (this._pickable) {
  50179. var nbfaces = meshInd.length / 3;
  50180. for (i = 0; i < nbfaces; i++) {
  50181. this.pickedParticles.push({ idx: idx, faceId: i });
  50182. }
  50183. }
  50184. if (this._depthSort) {
  50185. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  50186. }
  50187. return this._copy;
  50188. };
  50189. // returns a shape array from positions array
  50190. SolidParticleSystem.prototype._posToShape = function (positions) {
  50191. var shape = [];
  50192. for (var i = 0; i < positions.length; i += 3) {
  50193. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50194. }
  50195. return shape;
  50196. };
  50197. // returns a shapeUV array from a Vector4 uvs
  50198. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50199. var shapeUV = [];
  50200. if (uvs) {
  50201. for (var i = 0; i < uvs.length; i++)
  50202. shapeUV.push(uvs[i]);
  50203. }
  50204. return shapeUV;
  50205. };
  50206. // adds a new particle object in the particles array
  50207. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  50208. if (bInfo === void 0) { bInfo = null; }
  50209. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  50210. this.particles.push(sp);
  50211. return sp;
  50212. };
  50213. /**
  50214. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50215. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50216. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  50217. * @param nb (positive integer) the number of particles to be created from this model
  50218. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  50219. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  50220. * @returns the number of shapes in the system
  50221. */
  50222. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50223. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50224. var meshInd = mesh.getIndices();
  50225. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50226. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50227. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50228. var bbInfo;
  50229. if (this._particlesIntersect) {
  50230. bbInfo = mesh.getBoundingInfo();
  50231. }
  50232. var shape = this._posToShape(meshPos);
  50233. var shapeUV = this._uvsToShapeUV(meshUV);
  50234. var posfunc = options ? options.positionFunction : null;
  50235. var vtxfunc = options ? options.vertexFunction : null;
  50236. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  50237. // particles
  50238. var sp;
  50239. var currentCopy;
  50240. var idx = this.nbParticles;
  50241. for (var i = 0; i < nb; i++) {
  50242. var currentPos = this._positions.length;
  50243. var currentInd = this._indices.length;
  50244. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50245. if (this._updatable) {
  50246. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  50247. sp.position.copyFrom(currentCopy.position);
  50248. sp.rotation.copyFrom(currentCopy.rotation);
  50249. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  50250. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  50251. }
  50252. if (currentCopy.color && sp.color) {
  50253. sp.color.copyFrom(currentCopy.color);
  50254. }
  50255. sp.scaling.copyFrom(currentCopy.scaling);
  50256. sp.uvs.copyFrom(currentCopy.uvs);
  50257. }
  50258. this._index += shape.length;
  50259. idx++;
  50260. }
  50261. this.nbParticles += nb;
  50262. this._shapeCounter++;
  50263. return this._shapeCounter - 1;
  50264. };
  50265. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50266. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50267. this._resetCopy();
  50268. if (particle._model._positionFunction) {
  50269. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50270. }
  50271. if (this._copy.rotationQuaternion) {
  50272. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50273. }
  50274. else {
  50275. this._yaw = this._copy.rotation.y;
  50276. this._pitch = this._copy.rotation.x;
  50277. this._roll = this._copy.rotation.z;
  50278. this._quaternionRotationYPR();
  50279. }
  50280. this._quaternionToRotationMatrix();
  50281. this._shape = particle._model._shape;
  50282. for (var pt = 0; pt < this._shape.length; pt++) {
  50283. this._vertex.x = this._shape[pt].x;
  50284. this._vertex.y = this._shape[pt].y;
  50285. this._vertex.z = this._shape[pt].z;
  50286. if (particle._model._vertexFunction) {
  50287. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50288. }
  50289. this._vertex.x *= this._copy.scaling.x;
  50290. this._vertex.y *= this._copy.scaling.y;
  50291. this._vertex.z *= this._copy.scaling.z;
  50292. this._vertex.x += this._copy.pivot.x;
  50293. this._vertex.y += this._copy.pivot.y;
  50294. this._vertex.z += this._copy.pivot.z;
  50295. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50296. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50297. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50298. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50299. }
  50300. particle.position.x = 0.0;
  50301. particle.position.y = 0.0;
  50302. particle.position.z = 0.0;
  50303. particle.rotation.x = 0.0;
  50304. particle.rotation.y = 0.0;
  50305. particle.rotation.z = 0.0;
  50306. particle.rotationQuaternion = null;
  50307. particle.scaling.x = 1.0;
  50308. particle.scaling.y = 1.0;
  50309. particle.scaling.z = 1.0;
  50310. };
  50311. /**
  50312. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50313. * @returns the SPS.
  50314. */
  50315. SolidParticleSystem.prototype.rebuildMesh = function () {
  50316. for (var p = 0; p < this.particles.length; p++) {
  50317. this._rebuildParticle(this.particles[p]);
  50318. }
  50319. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50320. return this;
  50321. };
  50322. /**
  50323. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50324. * This method calls `updateParticle()` for each particle of the SPS.
  50325. * For an animated SPS, it is usually called within the render loop.
  50326. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50327. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50328. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50329. * @returns the SPS.
  50330. */
  50331. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50332. if (start === void 0) { start = 0; }
  50333. if (end === void 0) { end = this.nbParticles - 1; }
  50334. if (update === void 0) { update = true; }
  50335. if (!this._updatable) {
  50336. return this;
  50337. }
  50338. // custom beforeUpdate
  50339. this.beforeUpdateParticles(start, end, update);
  50340. this._cam_axisX.x = 1.0;
  50341. this._cam_axisX.y = 0.0;
  50342. this._cam_axisX.z = 0.0;
  50343. this._cam_axisY.x = 0.0;
  50344. this._cam_axisY.y = 1.0;
  50345. this._cam_axisY.z = 0.0;
  50346. this._cam_axisZ.x = 0.0;
  50347. this._cam_axisZ.y = 0.0;
  50348. this._cam_axisZ.z = 1.0;
  50349. // cases when the World Matrix is to be computed first
  50350. if (this.billboard || this._depthSort) {
  50351. this.mesh.computeWorldMatrix(true);
  50352. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  50353. }
  50354. // if the particles will always face the camera
  50355. if (this.billboard) {
  50356. // compute the camera position and un-rotate it by the current mesh rotation
  50357. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  50358. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50359. this._cam_axisZ.normalize();
  50360. // same for camera up vector extracted from the cam view matrix
  50361. var view = this._camera.getViewMatrix(true);
  50362. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  50363. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50364. this._cam_axisY.normalize();
  50365. this._cam_axisX.normalize();
  50366. }
  50367. // if depthSort, compute the camera global position in the mesh local system
  50368. if (this._depthSort) {
  50369. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  50370. }
  50371. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50372. var idx = 0; // current position index in the global array positions32
  50373. var index = 0; // position start index in the global array positions32 of the current particle
  50374. var colidx = 0; // current color index in the global array colors32
  50375. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50376. var uvidx = 0; // current uv index in the global array uvs32
  50377. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50378. var pt = 0; // current index in the particle model shape
  50379. if (this.mesh.isFacetDataEnabled) {
  50380. this._computeBoundingBox = true;
  50381. }
  50382. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  50383. if (this._computeBoundingBox) {
  50384. if (start == 0 && end == this.nbParticles - 1) {
  50385. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50386. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50387. }
  50388. else {
  50389. if (this.mesh._boundingInfo) {
  50390. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  50391. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  50392. }
  50393. }
  50394. }
  50395. // particle loop
  50396. index = this.particles[start]._pos;
  50397. var vpos = (index / 3) | 0;
  50398. colorIndex = vpos * 4;
  50399. uvIndex = vpos * 2;
  50400. for (var p = start; p <= end; p++) {
  50401. this._particle = this.particles[p];
  50402. this._shape = this._particle._model._shape;
  50403. this._shapeUV = this._particle._model._shapeUV;
  50404. // call to custom user function to update the particle properties
  50405. this.updateParticle(this._particle);
  50406. // camera-particle distance for depth sorting
  50407. if (this._depthSort && this._depthSortParticles) {
  50408. var dsp = this.depthSortedParticles[p];
  50409. dsp.ind = this._particle._ind;
  50410. dsp.indicesLength = this._particle._model._indicesLength;
  50411. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  50412. }
  50413. // skip the computations for inactive or already invisible particles
  50414. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  50415. // increment indexes for the next particle
  50416. pt = this._shape.length;
  50417. index += pt * 3;
  50418. colorIndex += pt * 4;
  50419. uvIndex += pt * 2;
  50420. continue;
  50421. }
  50422. if (this._particle.isVisible) {
  50423. this._particle._stillInvisible = false; // un-mark permanent invisibility
  50424. // particle rotation matrix
  50425. if (this.billboard) {
  50426. this._particle.rotation.x = 0.0;
  50427. this._particle.rotation.y = 0.0;
  50428. }
  50429. if (this._computeParticleRotation || this.billboard) {
  50430. if (this._particle.rotationQuaternion) {
  50431. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50432. }
  50433. else {
  50434. this._yaw = this._particle.rotation.y;
  50435. this._pitch = this._particle.rotation.x;
  50436. this._roll = this._particle.rotation.z;
  50437. this._quaternionRotationYPR();
  50438. }
  50439. this._quaternionToRotationMatrix();
  50440. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  50441. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  50442. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  50443. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  50444. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  50445. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  50446. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  50447. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  50448. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  50449. }
  50450. // particle vertex loop
  50451. for (pt = 0; pt < this._shape.length; pt++) {
  50452. idx = index + pt * 3;
  50453. colidx = colorIndex + pt * 4;
  50454. uvidx = uvIndex + pt * 2;
  50455. this._vertex.x = this._shape[pt].x;
  50456. this._vertex.y = this._shape[pt].y;
  50457. this._vertex.z = this._shape[pt].z;
  50458. if (this._computeParticleVertex) {
  50459. this.updateParticleVertex(this._particle, this._vertex, pt);
  50460. }
  50461. // positions
  50462. this._vertex.x *= this._particle.scaling.x;
  50463. this._vertex.y *= this._particle.scaling.y;
  50464. this._vertex.z *= this._particle.scaling.z;
  50465. this._vertex.x += this._particle.pivot.x;
  50466. this._vertex.y += this._particle.pivot.y;
  50467. this._vertex.z += this._particle.pivot.z;
  50468. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50469. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50470. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50471. 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;
  50472. 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;
  50473. 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;
  50474. if (this._computeBoundingBox) {
  50475. if (this._positions32[idx] < this._minimum.x) {
  50476. this._minimum.x = this._positions32[idx];
  50477. }
  50478. if (this._positions32[idx] > this._maximum.x) {
  50479. this._maximum.x = this._positions32[idx];
  50480. }
  50481. if (this._positions32[idx + 1] < this._minimum.y) {
  50482. this._minimum.y = this._positions32[idx + 1];
  50483. }
  50484. if (this._positions32[idx + 1] > this._maximum.y) {
  50485. this._maximum.y = this._positions32[idx + 1];
  50486. }
  50487. if (this._positions32[idx + 2] < this._minimum.z) {
  50488. this._minimum.z = this._positions32[idx + 2];
  50489. }
  50490. if (this._positions32[idx + 2] > this._maximum.z) {
  50491. this._maximum.z = this._positions32[idx + 2];
  50492. }
  50493. }
  50494. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50495. if (!this._computeParticleVertex) {
  50496. this._normal.x = this._fixedNormal32[idx];
  50497. this._normal.y = this._fixedNormal32[idx + 1];
  50498. this._normal.z = this._fixedNormal32[idx + 2];
  50499. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  50500. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  50501. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  50502. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50503. 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;
  50504. 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;
  50505. }
  50506. if (this._computeParticleColor && this._particle.color) {
  50507. this._colors32[colidx] = this._particle.color.r;
  50508. this._colors32[colidx + 1] = this._particle.color.g;
  50509. this._colors32[colidx + 2] = this._particle.color.b;
  50510. this._colors32[colidx + 3] = this._particle.color.a;
  50511. }
  50512. if (this._computeParticleTexture) {
  50513. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50514. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50515. }
  50516. }
  50517. }
  50518. else {
  50519. this._particle._stillInvisible = true; // mark the particle as invisible
  50520. for (pt = 0; pt < this._shape.length; pt++) {
  50521. idx = index + pt * 3;
  50522. colidx = colorIndex + pt * 4;
  50523. uvidx = uvIndex + pt * 2;
  50524. this._positions32[idx] = 0.0;
  50525. this._positions32[idx + 1] = 0.0;
  50526. this._positions32[idx + 2] = 0.0;
  50527. this._normals32[idx] = 0.0;
  50528. this._normals32[idx + 1] = 0.0;
  50529. this._normals32[idx + 2] = 0.0;
  50530. if (this._computeParticleColor && this._particle.color) {
  50531. this._colors32[colidx] = this._particle.color.r;
  50532. this._colors32[colidx + 1] = this._particle.color.g;
  50533. this._colors32[colidx + 2] = this._particle.color.b;
  50534. this._colors32[colidx + 3] = this._particle.color.a;
  50535. }
  50536. if (this._computeParticleTexture) {
  50537. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50538. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50539. }
  50540. }
  50541. }
  50542. // if the particle intersections must be computed : update the bbInfo
  50543. if (this._particlesIntersect) {
  50544. var bInfo = this._particle._boundingInfo;
  50545. var bBox = bInfo.boundingBox;
  50546. var bSphere = bInfo.boundingSphere;
  50547. if (!this._bSphereOnly) {
  50548. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50549. for (var b = 0; b < bBox.vectors.length; b++) {
  50550. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50551. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50552. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50553. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50554. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50555. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50556. 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;
  50557. 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;
  50558. 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;
  50559. }
  50560. bBox._update(this.mesh._worldMatrix);
  50561. }
  50562. // place and scale the particle bouding sphere in the SPS local system, then update it
  50563. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50564. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50565. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50566. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50567. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50568. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50569. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50570. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50571. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50572. 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));
  50573. bSphere._update(this.mesh._worldMatrix);
  50574. }
  50575. // increment indexes for the next particle
  50576. index = idx + 3;
  50577. colorIndex = colidx + 4;
  50578. uvIndex = uvidx + 2;
  50579. }
  50580. // if the VBO must be updated
  50581. if (update) {
  50582. if (this._computeParticleColor) {
  50583. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50584. }
  50585. if (this._computeParticleTexture) {
  50586. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50587. }
  50588. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50589. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50590. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50591. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50592. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50593. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50594. for (var i = 0; i < this._normals32.length; i++) {
  50595. this._fixedNormal32[i] = this._normals32[i];
  50596. }
  50597. }
  50598. if (!this.mesh.areNormalsFrozen) {
  50599. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50600. }
  50601. }
  50602. if (this._depthSort && this._depthSortParticles) {
  50603. this.depthSortedParticles.sort(this._depthSortFunction);
  50604. var dspl = this.depthSortedParticles.length;
  50605. var sorted = 0;
  50606. var lind = 0;
  50607. var sind = 0;
  50608. var sid = 0;
  50609. for (sorted = 0; sorted < dspl; sorted++) {
  50610. lind = this.depthSortedParticles[sorted].indicesLength;
  50611. sind = this.depthSortedParticles[sorted].ind;
  50612. for (var i = 0; i < lind; i++) {
  50613. this._indices32[sid] = this._indices[sind + i];
  50614. sid++;
  50615. }
  50616. }
  50617. this.mesh.updateIndices(this._indices32);
  50618. }
  50619. }
  50620. if (this._computeBoundingBox) {
  50621. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50622. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50623. }
  50624. this.afterUpdateParticles(start, end, update);
  50625. return this;
  50626. };
  50627. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50628. this._halfroll = this._roll * 0.5;
  50629. this._halfpitch = this._pitch * 0.5;
  50630. this._halfyaw = this._yaw * 0.5;
  50631. this._sinRoll = Math.sin(this._halfroll);
  50632. this._cosRoll = Math.cos(this._halfroll);
  50633. this._sinPitch = Math.sin(this._halfpitch);
  50634. this._cosPitch = Math.cos(this._halfpitch);
  50635. this._sinYaw = Math.sin(this._halfyaw);
  50636. this._cosYaw = Math.cos(this._halfyaw);
  50637. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50638. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50639. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50640. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50641. };
  50642. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50643. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50644. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50645. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50646. this._rotMatrix.m[3] = 0;
  50647. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50648. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50649. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50650. this._rotMatrix.m[7] = 0;
  50651. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50652. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50653. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50654. this._rotMatrix.m[11] = 0;
  50655. this._rotMatrix.m[12] = 0;
  50656. this._rotMatrix.m[13] = 0;
  50657. this._rotMatrix.m[14] = 0;
  50658. this._rotMatrix.m[15] = 1.0;
  50659. };
  50660. /**
  50661. * Disposes the SPS.
  50662. */
  50663. SolidParticleSystem.prototype.dispose = function () {
  50664. this.mesh.dispose();
  50665. this.vars = null;
  50666. // drop references to internal big arrays for the GC
  50667. this._positions = null;
  50668. this._indices = null;
  50669. this._normals = null;
  50670. this._uvs = null;
  50671. this._colors = null;
  50672. this._indices32 = null;
  50673. this._positions32 = null;
  50674. this._normals32 = null;
  50675. this._fixedNormal32 = null;
  50676. this._uvs32 = null;
  50677. this._colors32 = null;
  50678. this.pickedParticles = null;
  50679. };
  50680. /**
  50681. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50682. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50683. * @returns the SPS.
  50684. */
  50685. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50686. if (!this._isVisibilityBoxLocked) {
  50687. this.mesh.refreshBoundingInfo();
  50688. }
  50689. return this;
  50690. };
  50691. /**
  50692. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50693. * @param size the size (float) of the visibility box
  50694. * note : this doesn't lock the SPS mesh bounding box.
  50695. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50696. */
  50697. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50698. var vis = size / 2;
  50699. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50700. };
  50701. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50702. /**
  50703. * Gets whether the SPS as always visible or not
  50704. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50705. */
  50706. get: function () {
  50707. return this._alwaysVisible;
  50708. },
  50709. /**
  50710. * Sets the SPS as always visible or not
  50711. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50712. */
  50713. set: function (val) {
  50714. this._alwaysVisible = val;
  50715. this.mesh.alwaysSelectAsActiveMesh = val;
  50716. },
  50717. enumerable: true,
  50718. configurable: true
  50719. });
  50720. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50721. /**
  50722. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50723. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50724. */
  50725. get: function () {
  50726. return this._isVisibilityBoxLocked;
  50727. },
  50728. /**
  50729. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50730. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50731. */
  50732. set: function (val) {
  50733. this._isVisibilityBoxLocked = val;
  50734. var boundingInfo = this.mesh.getBoundingInfo();
  50735. boundingInfo.isLocked = val;
  50736. },
  50737. enumerable: true,
  50738. configurable: true
  50739. });
  50740. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50741. /**
  50742. * Gets if `setParticles()` computes the particle rotations or not.
  50743. * Default value : true. The SPS is faster when it's set to false.
  50744. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50745. */
  50746. get: function () {
  50747. return this._computeParticleRotation;
  50748. },
  50749. /**
  50750. * Tells to `setParticles()` to compute the particle rotations or not.
  50751. * Default value : true. The SPS is faster when it's set to false.
  50752. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50753. */
  50754. set: function (val) {
  50755. this._computeParticleRotation = val;
  50756. },
  50757. enumerable: true,
  50758. configurable: true
  50759. });
  50760. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50761. /**
  50762. * Gets if `setParticles()` computes the particle colors or not.
  50763. * Default value : true. The SPS is faster when it's set to false.
  50764. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50765. */
  50766. get: function () {
  50767. return this._computeParticleColor;
  50768. },
  50769. /**
  50770. * Tells to `setParticles()` to compute the particle colors or not.
  50771. * Default value : true. The SPS is faster when it's set to false.
  50772. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50773. */
  50774. set: function (val) {
  50775. this._computeParticleColor = val;
  50776. },
  50777. enumerable: true,
  50778. configurable: true
  50779. });
  50780. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50781. /**
  50782. * Gets if `setParticles()` computes the particle textures or not.
  50783. * Default value : true. The SPS is faster when it's set to false.
  50784. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50785. */
  50786. get: function () {
  50787. return this._computeParticleTexture;
  50788. },
  50789. set: function (val) {
  50790. this._computeParticleTexture = val;
  50791. },
  50792. enumerable: true,
  50793. configurable: true
  50794. });
  50795. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50796. /**
  50797. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50798. * Default value : false. The SPS is faster when it's set to false.
  50799. * Note : the particle custom vertex positions aren't stored values.
  50800. */
  50801. get: function () {
  50802. return this._computeParticleVertex;
  50803. },
  50804. /**
  50805. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50806. * Default value : false. The SPS is faster when it's set to false.
  50807. * Note : the particle custom vertex positions aren't stored values.
  50808. */
  50809. set: function (val) {
  50810. this._computeParticleVertex = val;
  50811. },
  50812. enumerable: true,
  50813. configurable: true
  50814. });
  50815. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50816. /**
  50817. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50818. */
  50819. get: function () {
  50820. return this._computeBoundingBox;
  50821. },
  50822. /**
  50823. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50824. */
  50825. set: function (val) {
  50826. this._computeBoundingBox = val;
  50827. },
  50828. enumerable: true,
  50829. configurable: true
  50830. });
  50831. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50832. /**
  50833. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50834. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50835. * Default : `true`
  50836. */
  50837. get: function () {
  50838. return this._depthSortParticles;
  50839. },
  50840. /**
  50841. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50842. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50843. * Default : `true`
  50844. */
  50845. set: function (val) {
  50846. this._depthSortParticles = val;
  50847. },
  50848. enumerable: true,
  50849. configurable: true
  50850. });
  50851. // =======================================================================
  50852. // Particle behavior logic
  50853. // these following methods may be overwritten by the user to fit his needs
  50854. /**
  50855. * This function does nothing. It may be overwritten to set all the particle first values.
  50856. * The SPS doesn't call this function, you may have to call it by your own.
  50857. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50858. */
  50859. SolidParticleSystem.prototype.initParticles = function () {
  50860. };
  50861. /**
  50862. * This function does nothing. It may be overwritten to recycle a particle.
  50863. * The SPS doesn't call this function, you may have to call it by your own.
  50864. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50865. * @param particle The particle to recycle
  50866. * @returns the recycled particle
  50867. */
  50868. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50869. return particle;
  50870. };
  50871. /**
  50872. * Updates a particle : this function should be overwritten by the user.
  50873. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50874. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50875. * @example : just set a particle position or velocity and recycle conditions
  50876. * @param particle The particle to update
  50877. * @returns the updated particle
  50878. */
  50879. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50880. return particle;
  50881. };
  50882. /**
  50883. * Updates a vertex of a particle : it can be overwritten by the user.
  50884. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50885. * @param particle the current particle
  50886. * @param vertex the current index of the current particle
  50887. * @param pt the index of the current vertex in the particle shape
  50888. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50889. * @example : just set a vertex particle position
  50890. * @returns the updated vertex
  50891. */
  50892. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50893. return vertex;
  50894. };
  50895. /**
  50896. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50897. * This does nothing and may be overwritten by the user.
  50898. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50899. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50900. * @param update the boolean update value actually passed to setParticles()
  50901. */
  50902. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50903. };
  50904. /**
  50905. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50906. * This will be passed three parameters.
  50907. * This does nothing and may be overwritten by the user.
  50908. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50909. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50910. * @param update the boolean update value actually passed to setParticles()
  50911. */
  50912. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50913. };
  50914. return SolidParticleSystem;
  50915. }());
  50916. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50917. })(BABYLON || (BABYLON = {}));
  50918. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50919. var BABYLON;
  50920. (function (BABYLON) {
  50921. var ShaderMaterial = /** @class */ (function (_super) {
  50922. __extends(ShaderMaterial, _super);
  50923. function ShaderMaterial(name, scene, shaderPath, options) {
  50924. var _this = _super.call(this, name, scene) || this;
  50925. _this._textures = {};
  50926. _this._textureArrays = {};
  50927. _this._floats = {};
  50928. _this._ints = {};
  50929. _this._floatsArrays = {};
  50930. _this._colors3 = {};
  50931. _this._colors3Arrays = {};
  50932. _this._colors4 = {};
  50933. _this._vectors2 = {};
  50934. _this._vectors3 = {};
  50935. _this._vectors4 = {};
  50936. _this._matrices = {};
  50937. _this._matrices3x3 = {};
  50938. _this._matrices2x2 = {};
  50939. _this._vectors2Arrays = {};
  50940. _this._vectors3Arrays = {};
  50941. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50942. _this._shaderPath = shaderPath;
  50943. options.needAlphaBlending = options.needAlphaBlending || false;
  50944. options.needAlphaTesting = options.needAlphaTesting || false;
  50945. options.attributes = options.attributes || ["position", "normal", "uv"];
  50946. options.uniforms = options.uniforms || ["worldViewProjection"];
  50947. options.uniformBuffers = options.uniformBuffers || [];
  50948. options.samplers = options.samplers || [];
  50949. options.defines = options.defines || [];
  50950. _this._options = options;
  50951. return _this;
  50952. }
  50953. ShaderMaterial.prototype.getClassName = function () {
  50954. return "ShaderMaterial";
  50955. };
  50956. ShaderMaterial.prototype.needAlphaBlending = function () {
  50957. return this._options.needAlphaBlending;
  50958. };
  50959. ShaderMaterial.prototype.needAlphaTesting = function () {
  50960. return this._options.needAlphaTesting;
  50961. };
  50962. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50963. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50964. this._options.uniforms.push(uniformName);
  50965. }
  50966. };
  50967. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50968. if (this._options.samplers.indexOf(name) === -1) {
  50969. this._options.samplers.push(name);
  50970. }
  50971. this._textures[name] = texture;
  50972. return this;
  50973. };
  50974. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50975. if (this._options.samplers.indexOf(name) === -1) {
  50976. this._options.samplers.push(name);
  50977. }
  50978. this._checkUniform(name);
  50979. this._textureArrays[name] = textures;
  50980. return this;
  50981. };
  50982. ShaderMaterial.prototype.setFloat = function (name, value) {
  50983. this._checkUniform(name);
  50984. this._floats[name] = value;
  50985. return this;
  50986. };
  50987. ShaderMaterial.prototype.setInt = function (name, value) {
  50988. this._checkUniform(name);
  50989. this._ints[name] = value;
  50990. return this;
  50991. };
  50992. ShaderMaterial.prototype.setFloats = function (name, value) {
  50993. this._checkUniform(name);
  50994. this._floatsArrays[name] = value;
  50995. return this;
  50996. };
  50997. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50998. this._checkUniform(name);
  50999. this._colors3[name] = value;
  51000. return this;
  51001. };
  51002. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  51003. this._checkUniform(name);
  51004. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  51005. color.toArray(arr, arr.length);
  51006. return arr;
  51007. }, []);
  51008. return this;
  51009. };
  51010. ShaderMaterial.prototype.setColor4 = function (name, value) {
  51011. this._checkUniform(name);
  51012. this._colors4[name] = value;
  51013. return this;
  51014. };
  51015. ShaderMaterial.prototype.setVector2 = function (name, value) {
  51016. this._checkUniform(name);
  51017. this._vectors2[name] = value;
  51018. return this;
  51019. };
  51020. ShaderMaterial.prototype.setVector3 = function (name, value) {
  51021. this._checkUniform(name);
  51022. this._vectors3[name] = value;
  51023. return this;
  51024. };
  51025. ShaderMaterial.prototype.setVector4 = function (name, value) {
  51026. this._checkUniform(name);
  51027. this._vectors4[name] = value;
  51028. return this;
  51029. };
  51030. ShaderMaterial.prototype.setMatrix = function (name, value) {
  51031. this._checkUniform(name);
  51032. this._matrices[name] = value;
  51033. return this;
  51034. };
  51035. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  51036. this._checkUniform(name);
  51037. this._matrices3x3[name] = value;
  51038. return this;
  51039. };
  51040. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  51041. this._checkUniform(name);
  51042. this._matrices2x2[name] = value;
  51043. return this;
  51044. };
  51045. ShaderMaterial.prototype.setArray2 = function (name, value) {
  51046. this._checkUniform(name);
  51047. this._vectors2Arrays[name] = value;
  51048. return this;
  51049. };
  51050. ShaderMaterial.prototype.setArray3 = function (name, value) {
  51051. this._checkUniform(name);
  51052. this._vectors3Arrays[name] = value;
  51053. return this;
  51054. };
  51055. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51056. if (!mesh) {
  51057. return true;
  51058. }
  51059. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  51060. return false;
  51061. }
  51062. return false;
  51063. };
  51064. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  51065. var scene = this.getScene();
  51066. var engine = scene.getEngine();
  51067. if (!this.checkReadyOnEveryCall) {
  51068. if (this._renderId === scene.getRenderId()) {
  51069. if (this._checkCache(scene, mesh, useInstances)) {
  51070. return true;
  51071. }
  51072. }
  51073. }
  51074. // Instances
  51075. var defines = [];
  51076. var attribs = [];
  51077. var fallbacks = new BABYLON.EffectFallbacks();
  51078. if (useInstances) {
  51079. defines.push("#define INSTANCES");
  51080. }
  51081. for (var index = 0; index < this._options.defines.length; index++) {
  51082. defines.push(this._options.defines[index]);
  51083. }
  51084. for (var index = 0; index < this._options.attributes.length; index++) {
  51085. attribs.push(this._options.attributes[index]);
  51086. }
  51087. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  51088. attribs.push(BABYLON.VertexBuffer.ColorKind);
  51089. defines.push("#define VERTEXCOLOR");
  51090. }
  51091. // Bones
  51092. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  51093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51095. if (mesh.numBoneInfluencers > 4) {
  51096. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51097. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51098. }
  51099. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51100. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51101. fallbacks.addCPUSkinningFallback(0, mesh);
  51102. if (this._options.uniforms.indexOf("mBones") === -1) {
  51103. this._options.uniforms.push("mBones");
  51104. }
  51105. }
  51106. else {
  51107. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51108. }
  51109. // Textures
  51110. for (var name in this._textures) {
  51111. if (!this._textures[name].isReady()) {
  51112. return false;
  51113. }
  51114. }
  51115. // Alpha test
  51116. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  51117. defines.push("#define ALPHATEST");
  51118. }
  51119. var previousEffect = this._effect;
  51120. var join = defines.join("\n");
  51121. this._effect = engine.createEffect(this._shaderPath, {
  51122. attributes: attribs,
  51123. uniformsNames: this._options.uniforms,
  51124. uniformBuffersNames: this._options.uniformBuffers,
  51125. samplers: this._options.samplers,
  51126. defines: join,
  51127. fallbacks: fallbacks,
  51128. onCompiled: this.onCompiled,
  51129. onError: this.onError
  51130. }, engine);
  51131. if (!this._effect.isReady()) {
  51132. return false;
  51133. }
  51134. if (previousEffect !== this._effect) {
  51135. scene.resetCachedMaterial();
  51136. }
  51137. this._renderId = scene.getRenderId();
  51138. return true;
  51139. };
  51140. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  51141. var scene = this.getScene();
  51142. if (!this._effect) {
  51143. return;
  51144. }
  51145. if (this._options.uniforms.indexOf("world") !== -1) {
  51146. this._effect.setMatrix("world", world);
  51147. }
  51148. if (this._options.uniforms.indexOf("worldView") !== -1) {
  51149. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  51150. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  51151. }
  51152. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  51153. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  51154. }
  51155. };
  51156. ShaderMaterial.prototype.bind = function (world, mesh) {
  51157. // Std values
  51158. this.bindOnlyWorldMatrix(world);
  51159. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  51160. if (this._options.uniforms.indexOf("view") !== -1) {
  51161. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  51162. }
  51163. if (this._options.uniforms.indexOf("projection") !== -1) {
  51164. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  51165. }
  51166. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  51167. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  51168. }
  51169. // Bones
  51170. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  51171. var name;
  51172. // Texture
  51173. for (name in this._textures) {
  51174. this._effect.setTexture(name, this._textures[name]);
  51175. }
  51176. // Texture arrays
  51177. for (name in this._textureArrays) {
  51178. this._effect.setTextureArray(name, this._textureArrays[name]);
  51179. }
  51180. // Int
  51181. for (name in this._ints) {
  51182. this._effect.setInt(name, this._ints[name]);
  51183. }
  51184. // Float
  51185. for (name in this._floats) {
  51186. this._effect.setFloat(name, this._floats[name]);
  51187. }
  51188. // Floats
  51189. for (name in this._floatsArrays) {
  51190. this._effect.setArray(name, this._floatsArrays[name]);
  51191. }
  51192. // Color3
  51193. for (name in this._colors3) {
  51194. this._effect.setColor3(name, this._colors3[name]);
  51195. }
  51196. for (name in this._colors3Arrays) {
  51197. this._effect.setArray3(name, this._colors3Arrays[name]);
  51198. }
  51199. // Color4
  51200. for (name in this._colors4) {
  51201. var color = this._colors4[name];
  51202. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  51203. }
  51204. // Vector2
  51205. for (name in this._vectors2) {
  51206. this._effect.setVector2(name, this._vectors2[name]);
  51207. }
  51208. // Vector3
  51209. for (name in this._vectors3) {
  51210. this._effect.setVector3(name, this._vectors3[name]);
  51211. }
  51212. // Vector4
  51213. for (name in this._vectors4) {
  51214. this._effect.setVector4(name, this._vectors4[name]);
  51215. }
  51216. // Matrix
  51217. for (name in this._matrices) {
  51218. this._effect.setMatrix(name, this._matrices[name]);
  51219. }
  51220. // Matrix 3x3
  51221. for (name in this._matrices3x3) {
  51222. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  51223. }
  51224. // Matrix 2x2
  51225. for (name in this._matrices2x2) {
  51226. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  51227. }
  51228. // Vector2Array
  51229. for (name in this._vectors2Arrays) {
  51230. this._effect.setArray2(name, this._vectors2Arrays[name]);
  51231. }
  51232. // Vector3Array
  51233. for (name in this._vectors3Arrays) {
  51234. this._effect.setArray3(name, this._vectors3Arrays[name]);
  51235. }
  51236. }
  51237. this._afterBind(mesh);
  51238. };
  51239. ShaderMaterial.prototype.getActiveTextures = function () {
  51240. var activeTextures = _super.prototype.getActiveTextures.call(this);
  51241. for (var name in this._textures) {
  51242. activeTextures.push(this._textures[name]);
  51243. }
  51244. for (var name in this._textureArrays) {
  51245. var array = this._textureArrays[name];
  51246. for (var index = 0; index < array.length; index++) {
  51247. activeTextures.push(array[index]);
  51248. }
  51249. }
  51250. return activeTextures;
  51251. };
  51252. ShaderMaterial.prototype.hasTexture = function (texture) {
  51253. if (_super.prototype.hasTexture.call(this, texture)) {
  51254. return true;
  51255. }
  51256. for (var name in this._textures) {
  51257. if (this._textures[name] === texture) {
  51258. return true;
  51259. }
  51260. }
  51261. for (var name in this._textureArrays) {
  51262. var array = this._textureArrays[name];
  51263. for (var index = 0; index < array.length; index++) {
  51264. if (array[index] === texture) {
  51265. return true;
  51266. }
  51267. }
  51268. }
  51269. return false;
  51270. };
  51271. ShaderMaterial.prototype.clone = function (name) {
  51272. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  51273. return newShaderMaterial;
  51274. };
  51275. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51276. if (forceDisposeTextures) {
  51277. var name;
  51278. for (name in this._textures) {
  51279. this._textures[name].dispose();
  51280. }
  51281. for (name in this._textureArrays) {
  51282. var array = this._textureArrays[name];
  51283. for (var index = 0; index < array.length; index++) {
  51284. array[index].dispose();
  51285. }
  51286. }
  51287. }
  51288. this._textures = {};
  51289. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51290. };
  51291. ShaderMaterial.prototype.serialize = function () {
  51292. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51293. serializationObject.customType = "BABYLON.ShaderMaterial";
  51294. serializationObject.options = this._options;
  51295. serializationObject.shaderPath = this._shaderPath;
  51296. var name;
  51297. // Texture
  51298. serializationObject.textures = {};
  51299. for (name in this._textures) {
  51300. serializationObject.textures[name] = this._textures[name].serialize();
  51301. }
  51302. // Texture arrays
  51303. serializationObject.textureArrays = {};
  51304. for (name in this._textureArrays) {
  51305. serializationObject.textureArrays[name] = [];
  51306. var array = this._textureArrays[name];
  51307. for (var index = 0; index < array.length; index++) {
  51308. serializationObject.textureArrays[name].push(array[index].serialize());
  51309. }
  51310. }
  51311. // Float
  51312. serializationObject.floats = {};
  51313. for (name in this._floats) {
  51314. serializationObject.floats[name] = this._floats[name];
  51315. }
  51316. // Float s
  51317. serializationObject.FloatArrays = {};
  51318. for (name in this._floatsArrays) {
  51319. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  51320. }
  51321. // Color3
  51322. serializationObject.colors3 = {};
  51323. for (name in this._colors3) {
  51324. serializationObject.colors3[name] = this._colors3[name].asArray();
  51325. }
  51326. // Color3 array
  51327. serializationObject.colors3Arrays = {};
  51328. for (name in this._colors3Arrays) {
  51329. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  51330. }
  51331. // Color4
  51332. serializationObject.colors4 = {};
  51333. for (name in this._colors4) {
  51334. serializationObject.colors4[name] = this._colors4[name].asArray();
  51335. }
  51336. // Vector2
  51337. serializationObject.vectors2 = {};
  51338. for (name in this._vectors2) {
  51339. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  51340. }
  51341. // Vector3
  51342. serializationObject.vectors3 = {};
  51343. for (name in this._vectors3) {
  51344. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  51345. }
  51346. // Vector4
  51347. serializationObject.vectors4 = {};
  51348. for (name in this._vectors4) {
  51349. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  51350. }
  51351. // Matrix
  51352. serializationObject.matrices = {};
  51353. for (name in this._matrices) {
  51354. serializationObject.matrices[name] = this._matrices[name].asArray();
  51355. }
  51356. // Matrix 3x3
  51357. serializationObject.matrices3x3 = {};
  51358. for (name in this._matrices3x3) {
  51359. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  51360. }
  51361. // Matrix 2x2
  51362. serializationObject.matrices2x2 = {};
  51363. for (name in this._matrices2x2) {
  51364. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  51365. }
  51366. // Vector2Array
  51367. serializationObject.vectors2Arrays = {};
  51368. for (name in this._vectors2Arrays) {
  51369. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  51370. }
  51371. // Vector3Array
  51372. serializationObject.vectors3Arrays = {};
  51373. for (name in this._vectors3Arrays) {
  51374. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  51375. }
  51376. return serializationObject;
  51377. };
  51378. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  51379. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  51380. var name;
  51381. // Texture
  51382. for (name in source.textures) {
  51383. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  51384. }
  51385. // Texture arrays
  51386. for (name in source.textureArrays) {
  51387. var array = source.textureArrays[name];
  51388. var textureArray = new Array();
  51389. for (var index = 0; index < array.length; index++) {
  51390. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  51391. }
  51392. material.setTextureArray(name, textureArray);
  51393. }
  51394. // Float
  51395. for (name in source.floats) {
  51396. material.setFloat(name, source.floats[name]);
  51397. }
  51398. // Float s
  51399. for (name in source.floatsArrays) {
  51400. material.setFloats(name, source.floatsArrays[name]);
  51401. }
  51402. // Color3
  51403. for (name in source.colors3) {
  51404. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  51405. }
  51406. // Color3 arrays
  51407. for (name in source.colors3Arrays) {
  51408. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  51409. if (i % 3 === 0) {
  51410. arr.push([num]);
  51411. }
  51412. else {
  51413. arr[arr.length - 1].push(num);
  51414. }
  51415. return arr;
  51416. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  51417. material.setColor3Array(name, colors);
  51418. }
  51419. // Color4
  51420. for (name in source.colors4) {
  51421. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  51422. }
  51423. // Vector2
  51424. for (name in source.vectors2) {
  51425. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  51426. }
  51427. // Vector3
  51428. for (name in source.vectors3) {
  51429. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  51430. }
  51431. // Vector4
  51432. for (name in source.vectors4) {
  51433. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  51434. }
  51435. // Matrix
  51436. for (name in source.matrices) {
  51437. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  51438. }
  51439. // Matrix 3x3
  51440. for (name in source.matrices3x3) {
  51441. material.setMatrix3x3(name, source.matrices3x3[name]);
  51442. }
  51443. // Matrix 2x2
  51444. for (name in source.matrices2x2) {
  51445. material.setMatrix2x2(name, source.matrices2x2[name]);
  51446. }
  51447. // Vector2Array
  51448. for (name in source.vectors2Arrays) {
  51449. material.setArray2(name, source.vectors2Arrays[name]);
  51450. }
  51451. // Vector3Array
  51452. for (name in source.vectors3Arrays) {
  51453. material.setArray3(name, source.vectors3Arrays[name]);
  51454. }
  51455. return material;
  51456. };
  51457. return ShaderMaterial;
  51458. }(BABYLON.Material));
  51459. BABYLON.ShaderMaterial = ShaderMaterial;
  51460. })(BABYLON || (BABYLON = {}));
  51461. //# sourceMappingURL=babylon.shaderMaterial.js.map
  51462. var BABYLON;
  51463. (function (BABYLON) {
  51464. var GroundMesh = /** @class */ (function (_super) {
  51465. __extends(GroundMesh, _super);
  51466. function GroundMesh(name, scene) {
  51467. var _this = _super.call(this, name, scene) || this;
  51468. _this.generateOctree = false;
  51469. return _this;
  51470. }
  51471. GroundMesh.prototype.getClassName = function () {
  51472. return "GroundMesh";
  51473. };
  51474. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  51475. get: function () {
  51476. return Math.min(this._subdivisionsX, this._subdivisionsY);
  51477. },
  51478. enumerable: true,
  51479. configurable: true
  51480. });
  51481. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  51482. get: function () {
  51483. return this._subdivisionsX;
  51484. },
  51485. enumerable: true,
  51486. configurable: true
  51487. });
  51488. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  51489. get: function () {
  51490. return this._subdivisionsY;
  51491. },
  51492. enumerable: true,
  51493. configurable: true
  51494. });
  51495. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  51496. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  51497. this._subdivisionsX = chunksCount;
  51498. this._subdivisionsY = chunksCount;
  51499. this.subdivide(chunksCount);
  51500. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  51501. };
  51502. /**
  51503. * Returns a height (y) value in the Worl system :
  51504. * the ground altitude at the coordinates (x, z) expressed in the World system.
  51505. * Returns the ground y position if (x, z) are outside the ground surface.
  51506. */
  51507. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  51508. var world = this.getWorldMatrix();
  51509. var invMat = BABYLON.Tmp.Matrix[5];
  51510. world.invertToRef(invMat);
  51511. var tmpVect = BABYLON.Tmp.Vector3[8];
  51512. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  51513. x = tmpVect.x;
  51514. z = tmpVect.z;
  51515. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51516. return this.position.y;
  51517. }
  51518. if (!this._heightQuads || this._heightQuads.length == 0) {
  51519. this._initHeightQuads();
  51520. this._computeHeightQuads();
  51521. }
  51522. var facet = this._getFacetAt(x, z);
  51523. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  51524. // return y in the World system
  51525. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  51526. return tmpVect.y;
  51527. };
  51528. /**
  51529. * Returns a normalized vector (Vector3) orthogonal to the ground
  51530. * at the ground coordinates (x, z) expressed in the World system.
  51531. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  51532. */
  51533. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  51534. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  51535. this.getNormalAtCoordinatesToRef(x, z, normal);
  51536. return normal;
  51537. };
  51538. /**
  51539. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  51540. * at the ground coordinates (x, z) expressed in the World system.
  51541. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  51542. * Returns the GroundMesh.
  51543. */
  51544. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  51545. var world = this.getWorldMatrix();
  51546. var tmpMat = BABYLON.Tmp.Matrix[5];
  51547. world.invertToRef(tmpMat);
  51548. var tmpVect = BABYLON.Tmp.Vector3[8];
  51549. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  51550. x = tmpVect.x;
  51551. z = tmpVect.z;
  51552. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51553. return this;
  51554. }
  51555. if (!this._heightQuads || this._heightQuads.length == 0) {
  51556. this._initHeightQuads();
  51557. this._computeHeightQuads();
  51558. }
  51559. var facet = this._getFacetAt(x, z);
  51560. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51561. return this;
  51562. };
  51563. /**
  51564. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51565. * if the ground has been updated.
  51566. * This can be used in the render loop.
  51567. * Returns the GroundMesh.
  51568. */
  51569. GroundMesh.prototype.updateCoordinateHeights = function () {
  51570. if (!this._heightQuads || this._heightQuads.length == 0) {
  51571. this._initHeightQuads();
  51572. }
  51573. this._computeHeightQuads();
  51574. return this;
  51575. };
  51576. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51577. GroundMesh.prototype._getFacetAt = function (x, z) {
  51578. // retrieve col and row from x, z coordinates in the ground local system
  51579. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51580. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51581. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51582. var facet;
  51583. if (z < quad.slope.x * x + quad.slope.y) {
  51584. facet = quad.facet1;
  51585. }
  51586. else {
  51587. facet = quad.facet2;
  51588. }
  51589. return facet;
  51590. };
  51591. // Creates and populates the heightMap array with "facet" elements :
  51592. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51593. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51594. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51595. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51596. // Returns the GroundMesh.
  51597. GroundMesh.prototype._initHeightQuads = function () {
  51598. var subdivisionsX = this._subdivisionsX;
  51599. var subdivisionsY = this._subdivisionsY;
  51600. this._heightQuads = new Array();
  51601. for (var row = 0; row < subdivisionsY; row++) {
  51602. for (var col = 0; col < subdivisionsX; col++) {
  51603. 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) };
  51604. this._heightQuads[row * subdivisionsX + col] = quad;
  51605. }
  51606. }
  51607. return this;
  51608. };
  51609. // Compute each quad element values and update the the heightMap array :
  51610. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51611. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51612. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51613. // Returns the GroundMesh.
  51614. GroundMesh.prototype._computeHeightQuads = function () {
  51615. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51616. if (!positions) {
  51617. return this;
  51618. }
  51619. var v1 = BABYLON.Tmp.Vector3[3];
  51620. var v2 = BABYLON.Tmp.Vector3[2];
  51621. var v3 = BABYLON.Tmp.Vector3[1];
  51622. var v4 = BABYLON.Tmp.Vector3[0];
  51623. var v1v2 = BABYLON.Tmp.Vector3[4];
  51624. var v1v3 = BABYLON.Tmp.Vector3[5];
  51625. var v1v4 = BABYLON.Tmp.Vector3[6];
  51626. var norm1 = BABYLON.Tmp.Vector3[7];
  51627. var norm2 = BABYLON.Tmp.Vector3[8];
  51628. var i = 0;
  51629. var j = 0;
  51630. var k = 0;
  51631. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51632. var h = 0;
  51633. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51634. var d2 = 0;
  51635. var subdivisionsX = this._subdivisionsX;
  51636. var subdivisionsY = this._subdivisionsY;
  51637. for (var row = 0; row < subdivisionsY; row++) {
  51638. for (var col = 0; col < subdivisionsX; col++) {
  51639. i = col * 3;
  51640. j = row * (subdivisionsX + 1) * 3;
  51641. k = (row + 1) * (subdivisionsX + 1) * 3;
  51642. v1.x = positions[j + i];
  51643. v1.y = positions[j + i + 1];
  51644. v1.z = positions[j + i + 2];
  51645. v2.x = positions[j + i + 3];
  51646. v2.y = positions[j + i + 4];
  51647. v2.z = positions[j + i + 5];
  51648. v3.x = positions[k + i];
  51649. v3.y = positions[k + i + 1];
  51650. v3.z = positions[k + i + 2];
  51651. v4.x = positions[k + i + 3];
  51652. v4.y = positions[k + i + 4];
  51653. v4.z = positions[k + i + 5];
  51654. // 2D slope V1V4
  51655. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51656. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51657. // facet equations :
  51658. // we compute each facet normal vector
  51659. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51660. // we compute the value d by applying the equation to v1 which belongs to the plane
  51661. // then we store the facet equation in a Vector4
  51662. v2.subtractToRef(v1, v1v2);
  51663. v3.subtractToRef(v1, v1v3);
  51664. v4.subtractToRef(v1, v1v4);
  51665. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51666. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51667. norm1.normalize();
  51668. norm2.normalize();
  51669. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51670. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51671. var quad = this._heightQuads[row * subdivisionsX + col];
  51672. quad.slope.copyFromFloats(cd, h);
  51673. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51674. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51675. }
  51676. }
  51677. return this;
  51678. };
  51679. GroundMesh.prototype.serialize = function (serializationObject) {
  51680. _super.prototype.serialize.call(this, serializationObject);
  51681. serializationObject.subdivisionsX = this._subdivisionsX;
  51682. serializationObject.subdivisionsY = this._subdivisionsY;
  51683. serializationObject.minX = this._minX;
  51684. serializationObject.maxX = this._maxX;
  51685. serializationObject.minZ = this._minZ;
  51686. serializationObject.maxZ = this._maxZ;
  51687. serializationObject.width = this._width;
  51688. serializationObject.height = this._height;
  51689. };
  51690. GroundMesh.Parse = function (parsedMesh, scene) {
  51691. var result = new GroundMesh(parsedMesh.name, scene);
  51692. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51693. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51694. result._minX = parsedMesh.minX;
  51695. result._maxX = parsedMesh.maxX;
  51696. result._minZ = parsedMesh.minZ;
  51697. result._maxZ = parsedMesh.maxZ;
  51698. result._width = parsedMesh.width;
  51699. result._height = parsedMesh.height;
  51700. return result;
  51701. };
  51702. return GroundMesh;
  51703. }(BABYLON.Mesh));
  51704. BABYLON.GroundMesh = GroundMesh;
  51705. })(BABYLON || (BABYLON = {}));
  51706. //# sourceMappingURL=babylon.groundMesh.js.map
  51707. var BABYLON;
  51708. (function (BABYLON) {
  51709. /**
  51710. * Creates an instance based on a source mesh.
  51711. */
  51712. var InstancedMesh = /** @class */ (function (_super) {
  51713. __extends(InstancedMesh, _super);
  51714. function InstancedMesh(name, source) {
  51715. var _this = _super.call(this, name, source.getScene()) || this;
  51716. source.instances.push(_this);
  51717. _this._sourceMesh = source;
  51718. _this.position.copyFrom(source.position);
  51719. _this.rotation.copyFrom(source.rotation);
  51720. _this.scaling.copyFrom(source.scaling);
  51721. if (source.rotationQuaternion) {
  51722. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51723. }
  51724. _this.infiniteDistance = source.infiniteDistance;
  51725. _this.setPivotMatrix(source.getPivotMatrix());
  51726. _this.refreshBoundingInfo();
  51727. _this._syncSubMeshes();
  51728. return _this;
  51729. }
  51730. /**
  51731. * Returns the string "InstancedMesh".
  51732. */
  51733. InstancedMesh.prototype.getClassName = function () {
  51734. return "InstancedMesh";
  51735. };
  51736. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51737. // Methods
  51738. get: function () {
  51739. return this._sourceMesh.receiveShadows;
  51740. },
  51741. enumerable: true,
  51742. configurable: true
  51743. });
  51744. Object.defineProperty(InstancedMesh.prototype, "material", {
  51745. get: function () {
  51746. return this._sourceMesh.material;
  51747. },
  51748. enumerable: true,
  51749. configurable: true
  51750. });
  51751. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51752. get: function () {
  51753. return this._sourceMesh.visibility;
  51754. },
  51755. enumerable: true,
  51756. configurable: true
  51757. });
  51758. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51759. get: function () {
  51760. return this._sourceMesh.skeleton;
  51761. },
  51762. enumerable: true,
  51763. configurable: true
  51764. });
  51765. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51766. get: function () {
  51767. return this._sourceMesh.renderingGroupId;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. /**
  51773. * Returns the total number of vertices (integer).
  51774. */
  51775. InstancedMesh.prototype.getTotalVertices = function () {
  51776. return this._sourceMesh.getTotalVertices();
  51777. };
  51778. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51779. get: function () {
  51780. return this._sourceMesh;
  51781. },
  51782. enumerable: true,
  51783. configurable: true
  51784. });
  51785. /**
  51786. * Is this node ready to be used/rendered
  51787. * @return {boolean} is it ready
  51788. */
  51789. InstancedMesh.prototype.isReady = function () {
  51790. return this._sourceMesh.isReady(true);
  51791. };
  51792. /**
  51793. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51794. */
  51795. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51796. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51797. };
  51798. /**
  51799. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51800. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51801. * The `data` are either a numeric array either a Float32Array.
  51802. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51803. * 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).
  51804. * Note that a new underlying VertexBuffer object is created each call.
  51805. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51806. *
  51807. * Possible `kind` values :
  51808. * - BABYLON.VertexBuffer.PositionKind
  51809. * - BABYLON.VertexBuffer.UVKind
  51810. * - BABYLON.VertexBuffer.UV2Kind
  51811. * - BABYLON.VertexBuffer.UV3Kind
  51812. * - BABYLON.VertexBuffer.UV4Kind
  51813. * - BABYLON.VertexBuffer.UV5Kind
  51814. * - BABYLON.VertexBuffer.UV6Kind
  51815. * - BABYLON.VertexBuffer.ColorKind
  51816. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51817. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51818. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51819. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51820. *
  51821. * Returns the Mesh.
  51822. */
  51823. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51824. if (this.sourceMesh) {
  51825. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51826. }
  51827. return this.sourceMesh;
  51828. };
  51829. /**
  51830. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51831. * If the mesh has no geometry, it is simply returned as it is.
  51832. * The `data` are either a numeric array either a Float32Array.
  51833. * No new underlying VertexBuffer object is created.
  51834. * 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.
  51835. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51836. *
  51837. * Possible `kind` values :
  51838. * - BABYLON.VertexBuffer.PositionKind
  51839. * - BABYLON.VertexBuffer.UVKind
  51840. * - BABYLON.VertexBuffer.UV2Kind
  51841. * - BABYLON.VertexBuffer.UV3Kind
  51842. * - BABYLON.VertexBuffer.UV4Kind
  51843. * - BABYLON.VertexBuffer.UV5Kind
  51844. * - BABYLON.VertexBuffer.UV6Kind
  51845. * - BABYLON.VertexBuffer.ColorKind
  51846. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51847. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51848. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51849. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51850. *
  51851. * Returns the Mesh.
  51852. */
  51853. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51854. if (this.sourceMesh) {
  51855. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51856. }
  51857. return this.sourceMesh;
  51858. };
  51859. /**
  51860. * Sets the mesh indices.
  51861. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51862. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51863. * This method creates a new index buffer each call.
  51864. * Returns the Mesh.
  51865. */
  51866. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51867. if (totalVertices === void 0) { totalVertices = null; }
  51868. if (this.sourceMesh) {
  51869. this.sourceMesh.setIndices(indices, totalVertices);
  51870. }
  51871. return this.sourceMesh;
  51872. };
  51873. /**
  51874. * Boolean : True if the mesh owns the requested kind of data.
  51875. */
  51876. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51877. return this._sourceMesh.isVerticesDataPresent(kind);
  51878. };
  51879. /**
  51880. * Returns an array of indices (IndicesArray).
  51881. */
  51882. InstancedMesh.prototype.getIndices = function () {
  51883. return this._sourceMesh.getIndices();
  51884. };
  51885. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51886. get: function () {
  51887. return this._sourceMesh._positions;
  51888. },
  51889. enumerable: true,
  51890. configurable: true
  51891. });
  51892. /**
  51893. * Sets a new updated BoundingInfo to the mesh.
  51894. * Returns the mesh.
  51895. */
  51896. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51897. var meshBB = this._sourceMesh.getBoundingInfo();
  51898. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51899. this._updateBoundingInfo();
  51900. return this;
  51901. };
  51902. InstancedMesh.prototype._preActivate = function () {
  51903. if (this._currentLOD) {
  51904. this._currentLOD._preActivate();
  51905. }
  51906. return this;
  51907. };
  51908. InstancedMesh.prototype._activate = function (renderId) {
  51909. if (this._currentLOD) {
  51910. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51911. }
  51912. return this;
  51913. };
  51914. /**
  51915. * Returns the current associated LOD AbstractMesh.
  51916. */
  51917. InstancedMesh.prototype.getLOD = function (camera) {
  51918. if (!camera) {
  51919. return this;
  51920. }
  51921. var boundingInfo = this.getBoundingInfo();
  51922. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51923. if (this._currentLOD === this.sourceMesh) {
  51924. return this;
  51925. }
  51926. return this._currentLOD;
  51927. };
  51928. InstancedMesh.prototype._syncSubMeshes = function () {
  51929. this.releaseSubMeshes();
  51930. if (this._sourceMesh.subMeshes) {
  51931. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51932. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51933. }
  51934. }
  51935. return this;
  51936. };
  51937. InstancedMesh.prototype._generatePointsArray = function () {
  51938. return this._sourceMesh._generatePointsArray();
  51939. };
  51940. /**
  51941. * Creates a new InstancedMesh from the current mesh.
  51942. * - name (string) : the cloned mesh name
  51943. * - newParent (optional Node) : the optional Node to parent the clone to.
  51944. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51945. *
  51946. * Returns the clone.
  51947. */
  51948. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51949. var result = this._sourceMesh.createInstance(name);
  51950. // Deep copy
  51951. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51952. // Bounding info
  51953. this.refreshBoundingInfo();
  51954. // Parent
  51955. if (newParent) {
  51956. result.parent = newParent;
  51957. }
  51958. if (!doNotCloneChildren) {
  51959. // Children
  51960. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51961. var mesh = this.getScene().meshes[index];
  51962. if (mesh.parent === this) {
  51963. mesh.clone(mesh.name, result);
  51964. }
  51965. }
  51966. }
  51967. result.computeWorldMatrix(true);
  51968. return result;
  51969. };
  51970. /**
  51971. * Disposes the InstancedMesh.
  51972. * Returns nothing.
  51973. */
  51974. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51975. // Remove from mesh
  51976. var index = this._sourceMesh.instances.indexOf(this);
  51977. this._sourceMesh.instances.splice(index, 1);
  51978. _super.prototype.dispose.call(this, doNotRecurse);
  51979. };
  51980. return InstancedMesh;
  51981. }(BABYLON.AbstractMesh));
  51982. BABYLON.InstancedMesh = InstancedMesh;
  51983. })(BABYLON || (BABYLON = {}));
  51984. //# sourceMappingURL=babylon.instancedMesh.js.map
  51985. var BABYLON;
  51986. (function (BABYLON) {
  51987. var LinesMesh = /** @class */ (function (_super) {
  51988. __extends(LinesMesh, _super);
  51989. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51990. if (scene === void 0) { scene = null; }
  51991. if (parent === void 0) { parent = null; }
  51992. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51993. _this.useVertexColor = useVertexColor;
  51994. _this.useVertexAlpha = useVertexAlpha;
  51995. _this.color = new BABYLON.Color3(1, 1, 1);
  51996. _this.alpha = 1;
  51997. if (source) {
  51998. _this.color = source.color.clone();
  51999. _this.alpha = source.alpha;
  52000. _this.useVertexColor = source.useVertexColor;
  52001. _this.useVertexAlpha = source.useVertexAlpha;
  52002. }
  52003. _this._intersectionThreshold = 0.1;
  52004. var defines = [];
  52005. var options = {
  52006. attributes: [BABYLON.VertexBuffer.PositionKind],
  52007. uniforms: ["world", "viewProjection"],
  52008. needAlphaBlending: true,
  52009. defines: defines
  52010. };
  52011. if (useVertexAlpha === false) {
  52012. options.needAlphaBlending = false;
  52013. }
  52014. if (!useVertexColor) {
  52015. options.uniforms.push("color");
  52016. }
  52017. else {
  52018. options.defines.push("#define VERTEXCOLOR");
  52019. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  52020. }
  52021. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  52022. return _this;
  52023. }
  52024. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  52025. /**
  52026. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52027. * This margin is expressed in world space coordinates, so its value may vary.
  52028. * Default value is 0.1
  52029. * @returns the intersection Threshold value.
  52030. */
  52031. get: function () {
  52032. return this._intersectionThreshold;
  52033. },
  52034. /**
  52035. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52036. * This margin is expressed in world space coordinates, so its value may vary.
  52037. * @param value the new threshold to apply
  52038. */
  52039. set: function (value) {
  52040. if (this._intersectionThreshold === value) {
  52041. return;
  52042. }
  52043. this._intersectionThreshold = value;
  52044. if (this.geometry) {
  52045. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  52046. }
  52047. },
  52048. enumerable: true,
  52049. configurable: true
  52050. });
  52051. /**
  52052. * Returns the string "LineMesh"
  52053. */
  52054. LinesMesh.prototype.getClassName = function () {
  52055. return "LinesMesh";
  52056. };
  52057. Object.defineProperty(LinesMesh.prototype, "material", {
  52058. get: function () {
  52059. return this._colorShader;
  52060. },
  52061. set: function (value) {
  52062. // Do nothing
  52063. },
  52064. enumerable: true,
  52065. configurable: true
  52066. });
  52067. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  52068. get: function () {
  52069. return false;
  52070. },
  52071. enumerable: true,
  52072. configurable: true
  52073. });
  52074. LinesMesh.prototype.createInstance = function (name) {
  52075. throw new Error("LinesMeshes do not support createInstance.");
  52076. };
  52077. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  52078. if (!this._geometry) {
  52079. return this;
  52080. }
  52081. // VBOs
  52082. this._geometry._bind(this._colorShader.getEffect());
  52083. // Color
  52084. if (!this.useVertexColor) {
  52085. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  52086. }
  52087. return this;
  52088. };
  52089. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  52090. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  52091. return this;
  52092. }
  52093. var engine = this.getScene().getEngine();
  52094. // Draw order
  52095. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  52096. return this;
  52097. };
  52098. LinesMesh.prototype.dispose = function (doNotRecurse) {
  52099. this._colorShader.dispose();
  52100. _super.prototype.dispose.call(this, doNotRecurse);
  52101. };
  52102. /**
  52103. * Returns a new LineMesh object cloned from the current one.
  52104. */
  52105. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  52106. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  52107. };
  52108. return LinesMesh;
  52109. }(BABYLON.Mesh));
  52110. BABYLON.LinesMesh = LinesMesh;
  52111. })(BABYLON || (BABYLON = {}));
  52112. //# sourceMappingURL=babylon.linesMesh.js.map
  52113. var BABYLON;
  52114. (function (BABYLON) {
  52115. var MeshBuilder = /** @class */ (function () {
  52116. function MeshBuilder() {
  52117. }
  52118. MeshBuilder.updateSideOrientation = function (orientation) {
  52119. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  52120. return BABYLON.Mesh.DOUBLESIDE;
  52121. }
  52122. if (orientation === undefined || orientation === null) {
  52123. return BABYLON.Mesh.FRONTSIDE;
  52124. }
  52125. return orientation;
  52126. };
  52127. /**
  52128. * Creates a box mesh.
  52129. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  52130. * The parameter `size` sets the size (float) of each box side (default 1).
  52131. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  52132. * 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).
  52133. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52135. * 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).
  52136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52138. */
  52139. MeshBuilder.CreateBox = function (name, options, scene) {
  52140. if (scene === void 0) { scene = null; }
  52141. var box = new BABYLON.Mesh(name, scene);
  52142. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52143. box._originalBuilderSideOrientation = options.sideOrientation;
  52144. var vertexData = BABYLON.VertexData.CreateBox(options);
  52145. vertexData.applyToMesh(box, options.updatable);
  52146. return box;
  52147. };
  52148. /**
  52149. * Creates a sphere mesh.
  52150. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  52151. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  52152. * 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`).
  52153. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  52154. * 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
  52155. * 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).
  52156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52157. * 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).
  52158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52160. */
  52161. MeshBuilder.CreateSphere = function (name, options, scene) {
  52162. var sphere = new BABYLON.Mesh(name, scene);
  52163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52164. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52165. var vertexData = BABYLON.VertexData.CreateSphere(options);
  52166. vertexData.applyToMesh(sphere, options.updatable);
  52167. return sphere;
  52168. };
  52169. /**
  52170. * Creates a plane polygonal mesh. By default, this is a disc.
  52171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  52172. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  52173. * 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.
  52174. * 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
  52175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52176. * 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).
  52177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52179. */
  52180. MeshBuilder.CreateDisc = function (name, options, scene) {
  52181. if (scene === void 0) { scene = null; }
  52182. var disc = new BABYLON.Mesh(name, scene);
  52183. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52184. disc._originalBuilderSideOrientation = options.sideOrientation;
  52185. var vertexData = BABYLON.VertexData.CreateDisc(options);
  52186. vertexData.applyToMesh(disc, options.updatable);
  52187. return disc;
  52188. };
  52189. /**
  52190. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  52191. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  52192. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  52193. * 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`).
  52194. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  52195. * 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.
  52196. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52197. * 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).
  52198. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52200. */
  52201. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  52202. var sphere = new BABYLON.Mesh(name, scene);
  52203. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52204. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52205. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  52206. vertexData.applyToMesh(sphere, options.updatable);
  52207. return sphere;
  52208. };
  52209. ;
  52210. /**
  52211. * Creates a ribbon mesh.
  52212. * 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.
  52213. *
  52214. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  52215. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  52216. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  52217. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  52218. * 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.
  52219. * 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.
  52220. * 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
  52221. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52222. * 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).
  52223. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52224. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52225. * 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.
  52226. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  52227. * 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
  52228. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  52229. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  52230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52231. */
  52232. MeshBuilder.CreateRibbon = function (name, options, scene) {
  52233. if (scene === void 0) { scene = null; }
  52234. var pathArray = options.pathArray;
  52235. var closeArray = options.closeArray;
  52236. var closePath = options.closePath;
  52237. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52238. var instance = options.instance;
  52239. var updatable = options.updatable;
  52240. if (instance) {
  52241. // positionFunction : ribbon case
  52242. // only pathArray and sideOrientation parameters are taken into account for positions update
  52243. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  52244. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  52245. var positionFunction = function (positions) {
  52246. var minlg = pathArray[0].length;
  52247. var i = 0;
  52248. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  52249. for (var si = 1; si <= ns; si++) {
  52250. for (var p = 0; p < pathArray.length; p++) {
  52251. var path = pathArray[p];
  52252. var l = path.length;
  52253. minlg = (minlg < l) ? minlg : l;
  52254. var j = 0;
  52255. while (j < minlg) {
  52256. positions[i] = path[j].x;
  52257. positions[i + 1] = path[j].y;
  52258. positions[i + 2] = path[j].z;
  52259. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  52260. BABYLON.Tmp.Vector3[0].x = path[j].x;
  52261. }
  52262. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  52263. BABYLON.Tmp.Vector3[1].x = path[j].x;
  52264. }
  52265. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  52266. BABYLON.Tmp.Vector3[0].y = path[j].y;
  52267. }
  52268. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  52269. BABYLON.Tmp.Vector3[1].y = path[j].y;
  52270. }
  52271. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  52272. BABYLON.Tmp.Vector3[0].z = path[j].z;
  52273. }
  52274. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  52275. BABYLON.Tmp.Vector3[1].z = path[j].z;
  52276. }
  52277. j++;
  52278. i += 3;
  52279. }
  52280. if (instance._closePath) {
  52281. positions[i] = path[0].x;
  52282. positions[i + 1] = path[0].y;
  52283. positions[i + 2] = path[0].z;
  52284. i += 3;
  52285. }
  52286. }
  52287. }
  52288. };
  52289. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52290. positionFunction(positions);
  52291. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  52292. instance._boundingInfo.update(instance._worldMatrix);
  52293. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52294. if (options.colors) {
  52295. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52296. for (var c = 0; c < options.colors.length; c++) {
  52297. colors[c * 4] = options.colors[c].r;
  52298. colors[c * 4 + 1] = options.colors[c].g;
  52299. colors[c * 4 + 2] = options.colors[c].b;
  52300. colors[c * 4 + 3] = options.colors[c].a;
  52301. }
  52302. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  52303. }
  52304. if (options.uvs) {
  52305. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52306. for (var i = 0; i < options.uvs.length; i++) {
  52307. uvs[i * 2] = options.uvs[i].x;
  52308. uvs[i * 2 + 1] = options.uvs[i].y;
  52309. }
  52310. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  52311. }
  52312. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  52313. var indices = instance.getIndices();
  52314. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52315. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  52316. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  52317. if (instance._closePath) {
  52318. var indexFirst = 0;
  52319. var indexLast = 0;
  52320. for (var p = 0; p < pathArray.length; p++) {
  52321. indexFirst = instance._idx[p] * 3;
  52322. if (p + 1 < pathArray.length) {
  52323. indexLast = (instance._idx[p + 1] - 1) * 3;
  52324. }
  52325. else {
  52326. indexLast = normals.length - 3;
  52327. }
  52328. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  52329. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  52330. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  52331. normals[indexLast] = normals[indexFirst];
  52332. normals[indexLast + 1] = normals[indexFirst + 1];
  52333. normals[indexLast + 2] = normals[indexFirst + 2];
  52334. }
  52335. }
  52336. if (!(instance.areNormalsFrozen)) {
  52337. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  52338. }
  52339. }
  52340. return instance;
  52341. }
  52342. else {
  52343. var ribbon = new BABYLON.Mesh(name, scene);
  52344. ribbon._originalBuilderSideOrientation = sideOrientation;
  52345. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  52346. if (closePath) {
  52347. ribbon._idx = vertexData._idx;
  52348. }
  52349. ribbon._closePath = closePath;
  52350. ribbon._closeArray = closeArray;
  52351. vertexData.applyToMesh(ribbon, updatable);
  52352. return ribbon;
  52353. }
  52354. };
  52355. /**
  52356. * Creates a cylinder or a cone mesh.
  52357. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  52358. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  52359. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  52360. * 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.
  52361. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  52362. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  52363. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  52364. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  52365. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  52366. * 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).
  52367. * 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
  52368. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  52369. * 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
  52370. * 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.
  52371. * If `enclose` is false, a ring surface is one element.
  52372. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  52373. * 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
  52374. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52375. * 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).
  52376. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52378. */
  52379. MeshBuilder.CreateCylinder = function (name, options, scene) {
  52380. var cylinder = new BABYLON.Mesh(name, scene);
  52381. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52382. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  52383. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  52384. vertexData.applyToMesh(cylinder, options.updatable);
  52385. return cylinder;
  52386. };
  52387. /**
  52388. * Creates a torus mesh.
  52389. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  52390. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  52391. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  52392. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  52393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52394. * 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).
  52395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52397. */
  52398. MeshBuilder.CreateTorus = function (name, options, scene) {
  52399. var torus = new BABYLON.Mesh(name, scene);
  52400. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52401. torus._originalBuilderSideOrientation = options.sideOrientation;
  52402. var vertexData = BABYLON.VertexData.CreateTorus(options);
  52403. vertexData.applyToMesh(torus, options.updatable);
  52404. return torus;
  52405. };
  52406. /**
  52407. * Creates a torus knot mesh.
  52408. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  52409. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  52410. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  52411. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  52412. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  52413. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52414. * 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).
  52415. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52417. */
  52418. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  52419. var torusKnot = new BABYLON.Mesh(name, scene);
  52420. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52421. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  52422. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  52423. vertexData.applyToMesh(torusKnot, options.updatable);
  52424. return torusKnot;
  52425. };
  52426. /**
  52427. * Creates a line system mesh.
  52428. * A line system is a pool of many lines gathered in a single mesh.
  52429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  52430. * 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.
  52431. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  52432. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  52433. * 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
  52434. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  52435. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  52436. * 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
  52437. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  52438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52439. */
  52440. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  52441. var instance = options.instance;
  52442. var lines = options.lines;
  52443. var colors = options.colors;
  52444. if (instance) {
  52445. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52446. var vertexColor;
  52447. var lineColors;
  52448. if (colors) {
  52449. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52450. }
  52451. var i = 0;
  52452. var c = 0;
  52453. for (var l = 0; l < lines.length; l++) {
  52454. var points = lines[l];
  52455. for (var p = 0; p < points.length; p++) {
  52456. positions[i] = points[p].x;
  52457. positions[i + 1] = points[p].y;
  52458. positions[i + 2] = points[p].z;
  52459. if (colors && vertexColor) {
  52460. lineColors = colors[l];
  52461. vertexColor[c] = lineColors[p].r;
  52462. vertexColor[c + 1] = lineColors[p].g;
  52463. vertexColor[c + 2] = lineColors[p].b;
  52464. vertexColor[c + 3] = lineColors[p].a;
  52465. c += 4;
  52466. }
  52467. i += 3;
  52468. }
  52469. }
  52470. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52471. if (colors && vertexColor) {
  52472. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  52473. }
  52474. return instance;
  52475. }
  52476. // line system creation
  52477. var useVertexColor = (colors) ? true : false;
  52478. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  52479. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  52480. vertexData.applyToMesh(lineSystem, options.updatable);
  52481. return lineSystem;
  52482. };
  52483. /**
  52484. * Creates a line mesh.
  52485. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  52486. * 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.
  52487. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52488. * The parameter `points` is an array successive Vector3.
  52489. * 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
  52490. * The optional parameter `colors` is an array of successive Color4, one per line point.
  52491. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  52492. * When updating an instance, remember that only point positions can change, not the number of points.
  52493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52494. */
  52495. MeshBuilder.CreateLines = function (name, options, scene) {
  52496. if (scene === void 0) { scene = null; }
  52497. var colors = (options.colors) ? [options.colors] : null;
  52498. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  52499. return lines;
  52500. };
  52501. /**
  52502. * Creates a dashed line mesh.
  52503. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  52504. * 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.
  52505. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52506. * The parameter `points` is an array successive Vector3.
  52507. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  52508. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  52509. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  52510. * 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
  52511. * When updating an instance, remember that only point positions can change, not the number of points.
  52512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52513. */
  52514. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  52515. if (scene === void 0) { scene = null; }
  52516. var points = options.points;
  52517. var instance = options.instance;
  52518. var gapSize = options.gapSize || 1;
  52519. var dashSize = options.dashSize || 3;
  52520. if (instance) {
  52521. var positionFunction = function (positions) {
  52522. var curvect = BABYLON.Vector3.Zero();
  52523. var nbSeg = positions.length / 6;
  52524. var lg = 0;
  52525. var nb = 0;
  52526. var shft = 0;
  52527. var dashshft = 0;
  52528. var curshft = 0;
  52529. var p = 0;
  52530. var i = 0;
  52531. var j = 0;
  52532. for (i = 0; i < points.length - 1; i++) {
  52533. points[i + 1].subtractToRef(points[i], curvect);
  52534. lg += curvect.length();
  52535. }
  52536. shft = lg / nbSeg;
  52537. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  52538. for (i = 0; i < points.length - 1; i++) {
  52539. points[i + 1].subtractToRef(points[i], curvect);
  52540. nb = Math.floor(curvect.length() / shft);
  52541. curvect.normalize();
  52542. j = 0;
  52543. while (j < nb && p < positions.length) {
  52544. curshft = shft * j;
  52545. positions[p] = points[i].x + curshft * curvect.x;
  52546. positions[p + 1] = points[i].y + curshft * curvect.y;
  52547. positions[p + 2] = points[i].z + curshft * curvect.z;
  52548. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  52549. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  52550. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  52551. p += 6;
  52552. j++;
  52553. }
  52554. }
  52555. while (p < positions.length) {
  52556. positions[p] = points[i].x;
  52557. positions[p + 1] = points[i].y;
  52558. positions[p + 2] = points[i].z;
  52559. p += 3;
  52560. }
  52561. };
  52562. instance.updateMeshPositions(positionFunction, false);
  52563. return instance;
  52564. }
  52565. // dashed lines creation
  52566. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52567. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52568. vertexData.applyToMesh(dashedLines, options.updatable);
  52569. dashedLines.dashSize = dashSize;
  52570. dashedLines.gapSize = gapSize;
  52571. return dashedLines;
  52572. };
  52573. /**
  52574. * Creates an extruded shape mesh.
  52575. * 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.
  52576. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52577. *
  52578. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52579. * 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
  52580. * extruded along the Z axis.
  52581. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52582. * 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.
  52583. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52584. * 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
  52585. * 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
  52586. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52588. * 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).
  52589. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52590. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52592. */
  52593. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52594. if (scene === void 0) { scene = null; }
  52595. var path = options.path;
  52596. var shape = options.shape;
  52597. var scale = options.scale || 1;
  52598. var rotation = options.rotation || 0;
  52599. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52600. var updatable = options.updatable;
  52601. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52602. var instance = options.instance || null;
  52603. var invertUV = options.invertUV || false;
  52604. 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);
  52605. };
  52606. /**
  52607. * Creates an custom extruded shape mesh.
  52608. * 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.
  52609. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52610. *
  52611. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52612. * 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
  52613. * extruded along the Z axis.
  52614. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52615. * 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
  52616. * and the distance of this point from the begining of the path :
  52617. * ```javascript
  52618. * var rotationFunction = function(i, distance) {
  52619. * // do things
  52620. * return rotationValue; }
  52621. * ```
  52622. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52623. * 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
  52624. * and the distance of this point from the begining of the path :
  52625. * ```javascript
  52626. * var scaleFunction = function(i, distance) {
  52627. * // do things
  52628. * return scaleValue;}
  52629. * ```
  52630. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52631. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52632. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52633. * 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
  52634. * 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
  52635. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52637. * 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).
  52638. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52639. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52641. */
  52642. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52643. var path = options.path;
  52644. var shape = options.shape;
  52645. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52646. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52647. var ribbonCloseArray = options.ribbonCloseArray || false;
  52648. var ribbonClosePath = options.ribbonClosePath || false;
  52649. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52650. var updatable = options.updatable;
  52651. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52652. var instance = options.instance;
  52653. var invertUV = options.invertUV || false;
  52654. 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);
  52655. };
  52656. /**
  52657. * Creates lathe mesh.
  52658. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52659. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52660. *
  52661. * 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
  52662. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52663. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52664. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52665. * 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.
  52666. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52667. * 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
  52668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52669. * 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).
  52670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52671. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52673. */
  52674. MeshBuilder.CreateLathe = function (name, options, scene) {
  52675. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52676. var closed = (options.closed === undefined) ? true : options.closed;
  52677. var shape = options.shape;
  52678. var radius = options.radius || 1;
  52679. var tessellation = options.tessellation || 64;
  52680. var updatable = options.updatable;
  52681. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52682. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52683. var pi2 = Math.PI * 2;
  52684. var paths = new Array();
  52685. var invertUV = options.invertUV || false;
  52686. var i = 0;
  52687. var p = 0;
  52688. var step = pi2 / tessellation * arc;
  52689. var rotated;
  52690. var path = new Array();
  52691. ;
  52692. for (i = 0; i <= tessellation; i++) {
  52693. var path = [];
  52694. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52695. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52696. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52697. }
  52698. for (p = 0; p < shape.length; p++) {
  52699. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52700. path.push(rotated);
  52701. }
  52702. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52703. 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));
  52704. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52705. }
  52706. paths.push(path);
  52707. }
  52708. // lathe ribbon
  52709. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52710. return lathe;
  52711. };
  52712. /**
  52713. * Creates a plane mesh.
  52714. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52715. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52716. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52717. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52718. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52719. * 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).
  52720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52722. */
  52723. MeshBuilder.CreatePlane = function (name, options, scene) {
  52724. var plane = new BABYLON.Mesh(name, scene);
  52725. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52726. plane._originalBuilderSideOrientation = options.sideOrientation;
  52727. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52728. vertexData.applyToMesh(plane, options.updatable);
  52729. if (options.sourcePlane) {
  52730. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52731. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52732. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52733. plane.rotate(vectorProduct, product);
  52734. }
  52735. return plane;
  52736. };
  52737. /**
  52738. * Creates a ground mesh.
  52739. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52740. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52741. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52743. */
  52744. MeshBuilder.CreateGround = function (name, options, scene) {
  52745. var ground = new BABYLON.GroundMesh(name, scene);
  52746. ground._setReady(false);
  52747. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52748. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52749. ground._width = options.width || 1;
  52750. ground._height = options.height || 1;
  52751. ground._maxX = ground._width / 2;
  52752. ground._maxZ = ground._height / 2;
  52753. ground._minX = -ground._maxX;
  52754. ground._minZ = -ground._maxZ;
  52755. var vertexData = BABYLON.VertexData.CreateGround(options);
  52756. vertexData.applyToMesh(ground, options.updatable);
  52757. ground._setReady(true);
  52758. return ground;
  52759. };
  52760. /**
  52761. * Creates a tiled ground mesh.
  52762. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52763. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52764. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52765. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52766. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52767. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52768. * numbers of subdivisions on the ground width and height of each tile.
  52769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52770. */
  52771. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52772. var tiledGround = new BABYLON.Mesh(name, scene);
  52773. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52774. vertexData.applyToMesh(tiledGround, options.updatable);
  52775. return tiledGround;
  52776. };
  52777. /**
  52778. * Creates a ground mesh from a height map.
  52779. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52781. * The parameter `url` sets the URL of the height map image resource.
  52782. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52783. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52784. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52785. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52786. * 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.
  52787. * 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).
  52788. * This function is passed the newly built mesh :
  52789. * ```javascript
  52790. * function(mesh) { // do things
  52791. * return; }
  52792. * ```
  52793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52794. */
  52795. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52796. var width = options.width || 10.0;
  52797. var height = options.height || 10.0;
  52798. var subdivisions = options.subdivisions || 1 | 0;
  52799. var minHeight = options.minHeight || 0.0;
  52800. var maxHeight = options.maxHeight || 1.0;
  52801. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52802. var updatable = options.updatable;
  52803. var onReady = options.onReady;
  52804. var ground = new BABYLON.GroundMesh(name, scene);
  52805. ground._subdivisionsX = subdivisions;
  52806. ground._subdivisionsY = subdivisions;
  52807. ground._width = width;
  52808. ground._height = height;
  52809. ground._maxX = ground._width / 2.0;
  52810. ground._maxZ = ground._height / 2.0;
  52811. ground._minX = -ground._maxX;
  52812. ground._minZ = -ground._maxZ;
  52813. ground._setReady(false);
  52814. var onload = function (img) {
  52815. // Getting height map data
  52816. var canvas = document.createElement("canvas");
  52817. var context = canvas.getContext("2d");
  52818. if (!context) {
  52819. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52820. }
  52821. if (scene.isDisposed) {
  52822. return;
  52823. }
  52824. var bufferWidth = img.width;
  52825. var bufferHeight = img.height;
  52826. canvas.width = bufferWidth;
  52827. canvas.height = bufferHeight;
  52828. context.drawImage(img, 0, 0);
  52829. // Create VertexData from map data
  52830. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52831. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52832. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52833. width: width, height: height,
  52834. subdivisions: subdivisions,
  52835. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52836. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52837. });
  52838. vertexData.applyToMesh(ground, updatable);
  52839. ground._setReady(true);
  52840. //execute ready callback, if set
  52841. if (onReady) {
  52842. onReady(ground);
  52843. }
  52844. };
  52845. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52846. return ground;
  52847. };
  52848. /**
  52849. * Creates a polygon mesh.
  52850. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52851. * 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.
  52852. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52854. * 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).
  52855. * Remember you can only change the shape positions, not their number when updating a polygon.
  52856. */
  52857. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52858. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52859. var shape = options.shape;
  52860. var holes = options.holes || [];
  52861. var depth = options.depth || 0;
  52862. var contours = [];
  52863. var hole = [];
  52864. for (var i = 0; i < shape.length; i++) {
  52865. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52866. }
  52867. var epsilon = 0.00000001;
  52868. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52869. contours.pop();
  52870. }
  52871. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52872. for (var hNb = 0; hNb < holes.length; hNb++) {
  52873. hole = [];
  52874. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52875. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52876. }
  52877. polygonTriangulation.addHole(hole);
  52878. }
  52879. var polygon = polygonTriangulation.build(options.updatable, depth);
  52880. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52881. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52882. vertexData.applyToMesh(polygon, options.updatable);
  52883. return polygon;
  52884. };
  52885. ;
  52886. /**
  52887. * Creates an extruded polygon mesh, with depth in the Y direction.
  52888. * 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).
  52889. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52890. */
  52891. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52892. return MeshBuilder.CreatePolygon(name, options, scene);
  52893. };
  52894. ;
  52895. /**
  52896. * Creates a tube mesh.
  52897. * 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.
  52898. *
  52899. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52900. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52901. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52902. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52903. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52904. * 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.
  52905. * It must return a radius value (positive float) :
  52906. * ```javascript
  52907. * var radiusFunction = function(i, distance) {
  52908. * // do things
  52909. * return radius; }
  52910. * ```
  52911. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52912. * 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
  52913. * 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
  52914. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52915. * 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).
  52916. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52917. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52919. */
  52920. MeshBuilder.CreateTube = function (name, options, scene) {
  52921. var path = options.path;
  52922. var instance = options.instance;
  52923. var radius = 1.0;
  52924. if (instance) {
  52925. radius = instance.radius;
  52926. }
  52927. if (options.radius !== undefined) {
  52928. radius = options.radius;
  52929. }
  52930. ;
  52931. var tessellation = options.tessellation || 64 | 0;
  52932. var radiusFunction = options.radiusFunction || null;
  52933. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52934. var invertUV = options.invertUV || false;
  52935. var updatable = options.updatable;
  52936. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52937. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52938. // tube geometry
  52939. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52940. var tangents = path3D.getTangents();
  52941. var normals = path3D.getNormals();
  52942. var distances = path3D.getDistances();
  52943. var pi2 = Math.PI * 2;
  52944. var step = pi2 / tessellation * arc;
  52945. var returnRadius = function () { return radius; };
  52946. var radiusFunctionFinal = radiusFunction || returnRadius;
  52947. var circlePath;
  52948. var rad;
  52949. var normal;
  52950. var rotated;
  52951. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52952. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52953. for (var i = 0; i < path.length; i++) {
  52954. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52955. circlePath = Array(); // current circle array
  52956. normal = normals[i]; // current normal
  52957. for (var t = 0; t < tessellation; t++) {
  52958. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52959. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52960. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52961. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52962. circlePath[t] = rotated;
  52963. }
  52964. circlePaths[index] = circlePath;
  52965. index++;
  52966. }
  52967. // cap
  52968. var capPath = function (nbPoints, pathIndex) {
  52969. var pointCap = Array();
  52970. for (var i = 0; i < nbPoints; i++) {
  52971. pointCap.push(path[pathIndex]);
  52972. }
  52973. return pointCap;
  52974. };
  52975. switch (cap) {
  52976. case BABYLON.Mesh.NO_CAP:
  52977. break;
  52978. case BABYLON.Mesh.CAP_START:
  52979. circlePaths[0] = capPath(tessellation, 0);
  52980. circlePaths[1] = circlePaths[2].slice(0);
  52981. break;
  52982. case BABYLON.Mesh.CAP_END:
  52983. circlePaths[index] = circlePaths[index - 1].slice(0);
  52984. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52985. break;
  52986. case BABYLON.Mesh.CAP_ALL:
  52987. circlePaths[0] = capPath(tessellation, 0);
  52988. circlePaths[1] = circlePaths[2].slice(0);
  52989. circlePaths[index] = circlePaths[index - 1].slice(0);
  52990. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52991. break;
  52992. default:
  52993. break;
  52994. }
  52995. return circlePaths;
  52996. };
  52997. var path3D;
  52998. var pathArray;
  52999. if (instance) {
  53000. var arc = options.arc || instance.arc;
  53001. path3D = (instance.path3D).update(path);
  53002. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  53003. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  53004. instance.path3D = path3D;
  53005. instance.pathArray = pathArray;
  53006. instance.arc = arc;
  53007. instance.radius = radius;
  53008. return instance;
  53009. }
  53010. // tube creation
  53011. path3D = new BABYLON.Path3D(path);
  53012. var newPathArray = new Array();
  53013. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53014. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  53015. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  53016. tube.pathArray = pathArray;
  53017. tube.path3D = path3D;
  53018. tube.tessellation = tessellation;
  53019. tube.cap = cap;
  53020. tube.arc = options.arc;
  53021. tube.radius = radius;
  53022. return tube;
  53023. };
  53024. /**
  53025. * Creates a polyhedron mesh.
  53026. *
  53027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  53028. * 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
  53029. * to choose the wanted type.
  53030. * The parameter `size` (positive float, default 1) sets the polygon size.
  53031. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  53032. * 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`.
  53033. * 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
  53034. * 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)`).
  53035. * 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
  53036. * 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.
  53037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53038. * 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).
  53039. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53041. */
  53042. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  53043. var polyhedron = new BABYLON.Mesh(name, scene);
  53044. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53045. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  53046. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  53047. vertexData.applyToMesh(polyhedron, options.updatable);
  53048. return polyhedron;
  53049. };
  53050. /**
  53051. * Creates a decal mesh.
  53052. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  53053. * 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.
  53054. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  53055. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  53056. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  53057. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  53058. */
  53059. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  53060. var indices = sourceMesh.getIndices();
  53061. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53062. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53063. var position = options.position || BABYLON.Vector3.Zero();
  53064. var normal = options.normal || BABYLON.Vector3.Up();
  53065. var size = options.size || BABYLON.Vector3.One();
  53066. var angle = options.angle || 0;
  53067. // Getting correct rotation
  53068. if (!normal) {
  53069. var target = new BABYLON.Vector3(0, 0, 1);
  53070. var camera = sourceMesh.getScene().activeCamera;
  53071. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  53072. normal = camera.globalPosition.subtract(cameraWorldTarget);
  53073. }
  53074. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  53075. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  53076. var pitch = Math.atan2(normal.y, len);
  53077. // Matrix
  53078. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  53079. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  53080. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  53081. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  53082. var vertexData = new BABYLON.VertexData();
  53083. vertexData.indices = [];
  53084. vertexData.positions = [];
  53085. vertexData.normals = [];
  53086. vertexData.uvs = [];
  53087. var currentVertexDataIndex = 0;
  53088. var extractDecalVector3 = function (indexId) {
  53089. var result = new BABYLON.PositionNormalVertex();
  53090. if (!indices || !positions || !normals) {
  53091. return result;
  53092. }
  53093. var vertexId = indices[indexId];
  53094. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  53095. // Send vector to decal local world
  53096. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  53097. // Get normal
  53098. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  53099. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  53100. return result;
  53101. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  53102. var clip = function (vertices, axis) {
  53103. if (vertices.length === 0) {
  53104. return vertices;
  53105. }
  53106. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  53107. var clipVertices = function (v0, v1) {
  53108. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  53109. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  53110. };
  53111. var result = new Array();
  53112. for (var index = 0; index < vertices.length; index += 3) {
  53113. var v1Out;
  53114. var v2Out;
  53115. var v3Out;
  53116. var total = 0;
  53117. var nV1 = null;
  53118. var nV2 = null;
  53119. var nV3 = null;
  53120. var nV4 = null;
  53121. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  53122. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  53123. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  53124. v1Out = d1 > 0;
  53125. v2Out = d2 > 0;
  53126. v3Out = d3 > 0;
  53127. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  53128. switch (total) {
  53129. case 0:
  53130. result.push(vertices[index]);
  53131. result.push(vertices[index + 1]);
  53132. result.push(vertices[index + 2]);
  53133. break;
  53134. case 1:
  53135. if (v1Out) {
  53136. nV1 = vertices[index + 1];
  53137. nV2 = vertices[index + 2];
  53138. nV3 = clipVertices(vertices[index], nV1);
  53139. nV4 = clipVertices(vertices[index], nV2);
  53140. }
  53141. if (v2Out) {
  53142. nV1 = vertices[index];
  53143. nV2 = vertices[index + 2];
  53144. nV3 = clipVertices(vertices[index + 1], nV1);
  53145. nV4 = clipVertices(vertices[index + 1], nV2);
  53146. result.push(nV3);
  53147. result.push(nV2.clone());
  53148. result.push(nV1.clone());
  53149. result.push(nV2.clone());
  53150. result.push(nV3.clone());
  53151. result.push(nV4);
  53152. break;
  53153. }
  53154. if (v3Out) {
  53155. nV1 = vertices[index];
  53156. nV2 = vertices[index + 1];
  53157. nV3 = clipVertices(vertices[index + 2], nV1);
  53158. nV4 = clipVertices(vertices[index + 2], nV2);
  53159. }
  53160. if (nV1 && nV2 && nV3 && nV4) {
  53161. result.push(nV1.clone());
  53162. result.push(nV2.clone());
  53163. result.push(nV3);
  53164. result.push(nV4);
  53165. result.push(nV3.clone());
  53166. result.push(nV2.clone());
  53167. }
  53168. break;
  53169. case 2:
  53170. if (!v1Out) {
  53171. nV1 = vertices[index].clone();
  53172. nV2 = clipVertices(nV1, vertices[index + 1]);
  53173. nV3 = clipVertices(nV1, vertices[index + 2]);
  53174. result.push(nV1);
  53175. result.push(nV2);
  53176. result.push(nV3);
  53177. }
  53178. if (!v2Out) {
  53179. nV1 = vertices[index + 1].clone();
  53180. nV2 = clipVertices(nV1, vertices[index + 2]);
  53181. nV3 = clipVertices(nV1, vertices[index]);
  53182. result.push(nV1);
  53183. result.push(nV2);
  53184. result.push(nV3);
  53185. }
  53186. if (!v3Out) {
  53187. nV1 = vertices[index + 2].clone();
  53188. nV2 = clipVertices(nV1, vertices[index]);
  53189. nV3 = clipVertices(nV1, vertices[index + 1]);
  53190. result.push(nV1);
  53191. result.push(nV2);
  53192. result.push(nV3);
  53193. }
  53194. break;
  53195. case 3:
  53196. break;
  53197. }
  53198. }
  53199. return result;
  53200. };
  53201. for (var index = 0; index < indices.length; index += 3) {
  53202. var faceVertices = new Array();
  53203. faceVertices.push(extractDecalVector3(index));
  53204. faceVertices.push(extractDecalVector3(index + 1));
  53205. faceVertices.push(extractDecalVector3(index + 2));
  53206. // Clip
  53207. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  53208. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  53209. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  53210. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  53211. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  53212. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  53213. if (faceVertices.length === 0) {
  53214. continue;
  53215. }
  53216. // Add UVs and get back to world
  53217. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  53218. var vertex = faceVertices[vIndex];
  53219. //TODO check for Int32Array | Uint32Array | Uint16Array
  53220. vertexData.indices.push(currentVertexDataIndex);
  53221. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  53222. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  53223. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  53224. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  53225. currentVertexDataIndex++;
  53226. }
  53227. }
  53228. // Return mesh
  53229. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  53230. vertexData.applyToMesh(decal);
  53231. decal.position = position.clone();
  53232. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  53233. return decal;
  53234. };
  53235. // Privates
  53236. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  53237. // extrusion geometry
  53238. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  53239. var tangents = path3D.getTangents();
  53240. var normals = path3D.getNormals();
  53241. var binormals = path3D.getBinormals();
  53242. var distances = path3D.getDistances();
  53243. var angle = 0;
  53244. var returnScale = function () { return scale !== null ? scale : 1; };
  53245. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  53246. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  53247. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  53248. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53249. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53250. for (var i = 0; i < curve.length; i++) {
  53251. var shapePath = new Array();
  53252. var angleStep = rotate(i, distances[i]);
  53253. var scaleRatio = scl(i, distances[i]);
  53254. for (var p = 0; p < shape.length; p++) {
  53255. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  53256. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  53257. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  53258. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  53259. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  53260. shapePath[p] = rotated;
  53261. }
  53262. shapePaths[index] = shapePath;
  53263. angle += angleStep;
  53264. index++;
  53265. }
  53266. // cap
  53267. var capPath = function (shapePath) {
  53268. var pointCap = Array();
  53269. var barycenter = BABYLON.Vector3.Zero();
  53270. var i;
  53271. for (i = 0; i < shapePath.length; i++) {
  53272. barycenter.addInPlace(shapePath[i]);
  53273. }
  53274. barycenter.scaleInPlace(1.0 / shapePath.length);
  53275. for (i = 0; i < shapePath.length; i++) {
  53276. pointCap.push(barycenter);
  53277. }
  53278. return pointCap;
  53279. };
  53280. switch (cap) {
  53281. case BABYLON.Mesh.NO_CAP:
  53282. break;
  53283. case BABYLON.Mesh.CAP_START:
  53284. shapePaths[0] = capPath(shapePaths[2]);
  53285. shapePaths[1] = shapePaths[2];
  53286. break;
  53287. case BABYLON.Mesh.CAP_END:
  53288. shapePaths[index] = shapePaths[index - 1];
  53289. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53290. break;
  53291. case BABYLON.Mesh.CAP_ALL:
  53292. shapePaths[0] = capPath(shapePaths[2]);
  53293. shapePaths[1] = shapePaths[2];
  53294. shapePaths[index] = shapePaths[index - 1];
  53295. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53296. break;
  53297. default:
  53298. break;
  53299. }
  53300. return shapePaths;
  53301. };
  53302. var path3D;
  53303. var pathArray;
  53304. if (instance) {
  53305. path3D = (instance.path3D).update(curve);
  53306. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  53307. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  53308. return instance;
  53309. }
  53310. // extruded shape creation
  53311. path3D = new BABYLON.Path3D(curve);
  53312. var newShapePaths = new Array();
  53313. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53314. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  53315. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  53316. extrudedGeneric.pathArray = pathArray;
  53317. extrudedGeneric.path3D = path3D;
  53318. extrudedGeneric.cap = cap;
  53319. return extrudedGeneric;
  53320. };
  53321. return MeshBuilder;
  53322. }());
  53323. BABYLON.MeshBuilder = MeshBuilder;
  53324. })(BABYLON || (BABYLON = {}));
  53325. //# sourceMappingURL=babylon.meshBuilder.js.map
  53326. var BABYLON;
  53327. (function (BABYLON) {
  53328. var AudioEngine = /** @class */ (function () {
  53329. function AudioEngine() {
  53330. this._audioContext = null;
  53331. this._audioContextInitialized = false;
  53332. this.canUseWebAudio = false;
  53333. this.WarnedWebAudioUnsupported = false;
  53334. this.unlocked = false;
  53335. this.isMP3supported = false;
  53336. this.isOGGsupported = false;
  53337. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  53338. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  53339. this.canUseWebAudio = true;
  53340. }
  53341. var audioElem = document.createElement('audio');
  53342. try {
  53343. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  53344. this.isMP3supported = true;
  53345. }
  53346. }
  53347. catch (e) {
  53348. // protect error during capability check.
  53349. }
  53350. try {
  53351. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  53352. this.isOGGsupported = true;
  53353. }
  53354. }
  53355. catch (e) {
  53356. // protect error during capability check.
  53357. }
  53358. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  53359. this._unlockiOSaudio();
  53360. }
  53361. else {
  53362. this.unlocked = true;
  53363. }
  53364. }
  53365. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  53366. get: function () {
  53367. if (!this._audioContextInitialized) {
  53368. this._initializeAudioContext();
  53369. }
  53370. return this._audioContext;
  53371. },
  53372. enumerable: true,
  53373. configurable: true
  53374. });
  53375. AudioEngine.prototype._unlockiOSaudio = function () {
  53376. var _this = this;
  53377. var unlockaudio = function () {
  53378. if (!_this.audioContext) {
  53379. return;
  53380. }
  53381. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  53382. var source = _this.audioContext.createBufferSource();
  53383. source.buffer = buffer;
  53384. source.connect(_this.audioContext.destination);
  53385. source.start(0);
  53386. setTimeout(function () {
  53387. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  53388. _this.unlocked = true;
  53389. window.removeEventListener('touchend', unlockaudio, false);
  53390. if (_this.onAudioUnlocked) {
  53391. _this.onAudioUnlocked();
  53392. }
  53393. }
  53394. }, 0);
  53395. };
  53396. window.addEventListener('touchend', unlockaudio, false);
  53397. };
  53398. AudioEngine.prototype._initializeAudioContext = function () {
  53399. try {
  53400. if (this.canUseWebAudio) {
  53401. this._audioContext = new AudioContext();
  53402. // create a global volume gain node
  53403. this.masterGain = this._audioContext.createGain();
  53404. this.masterGain.gain.value = 1;
  53405. this.masterGain.connect(this._audioContext.destination);
  53406. this._audioContextInitialized = true;
  53407. }
  53408. }
  53409. catch (e) {
  53410. this.canUseWebAudio = false;
  53411. BABYLON.Tools.Error("Web Audio: " + e.message);
  53412. }
  53413. };
  53414. AudioEngine.prototype.dispose = function () {
  53415. if (this.canUseWebAudio && this._audioContextInitialized) {
  53416. if (this._connectedAnalyser && this._audioContext) {
  53417. this._connectedAnalyser.stopDebugCanvas();
  53418. this._connectedAnalyser.dispose();
  53419. this.masterGain.disconnect();
  53420. this.masterGain.connect(this._audioContext.destination);
  53421. this._connectedAnalyser = null;
  53422. }
  53423. this.masterGain.gain.value = 1;
  53424. }
  53425. this.WarnedWebAudioUnsupported = false;
  53426. };
  53427. AudioEngine.prototype.getGlobalVolume = function () {
  53428. if (this.canUseWebAudio && this._audioContextInitialized) {
  53429. return this.masterGain.gain.value;
  53430. }
  53431. else {
  53432. return -1;
  53433. }
  53434. };
  53435. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  53436. if (this.canUseWebAudio && this._audioContextInitialized) {
  53437. this.masterGain.gain.value = newVolume;
  53438. }
  53439. };
  53440. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  53441. if (this._connectedAnalyser) {
  53442. this._connectedAnalyser.stopDebugCanvas();
  53443. }
  53444. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  53445. this._connectedAnalyser = analyser;
  53446. this.masterGain.disconnect();
  53447. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  53448. }
  53449. };
  53450. return AudioEngine;
  53451. }());
  53452. BABYLON.AudioEngine = AudioEngine;
  53453. })(BABYLON || (BABYLON = {}));
  53454. //# sourceMappingURL=babylon.audioEngine.js.map
  53455. var BABYLON;
  53456. (function (BABYLON) {
  53457. var Sound = /** @class */ (function () {
  53458. /**
  53459. * Create a sound and attach it to a scene
  53460. * @param name Name of your sound
  53461. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  53462. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  53463. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53464. */
  53465. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  53466. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  53467. var _this = this;
  53468. this.autoplay = false;
  53469. this.loop = false;
  53470. this.useCustomAttenuation = false;
  53471. this.spatialSound = false;
  53472. this.refDistance = 1;
  53473. this.rolloffFactor = 1;
  53474. this.maxDistance = 100;
  53475. this.distanceModel = "linear";
  53476. this._panningModel = "equalpower";
  53477. this._playbackRate = 1;
  53478. this._streaming = false;
  53479. this._startTime = 0;
  53480. this._startOffset = 0;
  53481. this._position = BABYLON.Vector3.Zero();
  53482. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  53483. this._volume = 1;
  53484. this._isReadyToPlay = false;
  53485. this.isPlaying = false;
  53486. this.isPaused = false;
  53487. this._isDirectional = false;
  53488. // Used if you'd like to create a directional sound.
  53489. // If not set, the sound will be omnidirectional
  53490. this._coneInnerAngle = 360;
  53491. this._coneOuterAngle = 360;
  53492. this._coneOuterGain = 0;
  53493. this._isOutputConnected = false;
  53494. this._urlType = "Unknown";
  53495. this.name = name;
  53496. this._scene = scene;
  53497. this._readyToPlayCallback = readyToPlayCallback;
  53498. // Default custom attenuation function is a linear attenuation
  53499. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  53500. if (currentDistance < maxDistance) {
  53501. return currentVolume * (1 - currentDistance / maxDistance);
  53502. }
  53503. else {
  53504. return 0;
  53505. }
  53506. };
  53507. if (options) {
  53508. this.autoplay = options.autoplay || false;
  53509. this.loop = options.loop || false;
  53510. // if volume === 0, we need another way to check this option
  53511. if (options.volume !== undefined) {
  53512. this._volume = options.volume;
  53513. }
  53514. this.spatialSound = options.spatialSound || false;
  53515. this.maxDistance = options.maxDistance || 100;
  53516. this.useCustomAttenuation = options.useCustomAttenuation || false;
  53517. this.rolloffFactor = options.rolloffFactor || 1;
  53518. this.refDistance = options.refDistance || 1;
  53519. this.distanceModel = options.distanceModel || "linear";
  53520. this._playbackRate = options.playbackRate || 1;
  53521. this._streaming = options.streaming || false;
  53522. }
  53523. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53524. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  53525. this._soundGain.gain.value = this._volume;
  53526. this._inputAudioNode = this._soundGain;
  53527. this._ouputAudioNode = this._soundGain;
  53528. if (this.spatialSound) {
  53529. this._createSpatialParameters();
  53530. }
  53531. this._scene.mainSoundTrack.AddSound(this);
  53532. var validParameter = true;
  53533. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  53534. if (urlOrArrayBuffer) {
  53535. if (typeof (urlOrArrayBuffer) === "string")
  53536. this._urlType = "String";
  53537. if (Array.isArray(urlOrArrayBuffer))
  53538. this._urlType = "Array";
  53539. if (urlOrArrayBuffer instanceof ArrayBuffer)
  53540. this._urlType = "ArrayBuffer";
  53541. var urls = [];
  53542. var codecSupportedFound = false;
  53543. switch (this._urlType) {
  53544. case "ArrayBuffer":
  53545. if (urlOrArrayBuffer.byteLength > 0) {
  53546. codecSupportedFound = true;
  53547. this._soundLoaded(urlOrArrayBuffer);
  53548. }
  53549. break;
  53550. case "String":
  53551. urls.push(urlOrArrayBuffer);
  53552. case "Array":
  53553. if (urls.length === 0)
  53554. urls = urlOrArrayBuffer;
  53555. // If we found a supported format, we load it immediately and stop the loop
  53556. for (var i = 0; i < urls.length; i++) {
  53557. var url = urls[i];
  53558. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53559. codecSupportedFound = true;
  53560. }
  53561. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53562. codecSupportedFound = true;
  53563. }
  53564. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53565. codecSupportedFound = true;
  53566. }
  53567. if (url.indexOf("blob:") !== -1) {
  53568. codecSupportedFound = true;
  53569. }
  53570. if (codecSupportedFound) {
  53571. // Loading sound using XHR2
  53572. if (!this._streaming) {
  53573. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53574. }
  53575. else {
  53576. this._htmlAudioElement = new Audio(url);
  53577. this._htmlAudioElement.controls = false;
  53578. this._htmlAudioElement.loop = this.loop;
  53579. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53580. this._htmlAudioElement.preload = "auto";
  53581. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53582. _this._isReadyToPlay = true;
  53583. if (_this.autoplay) {
  53584. _this.play();
  53585. }
  53586. if (_this._readyToPlayCallback) {
  53587. _this._readyToPlayCallback();
  53588. }
  53589. });
  53590. document.body.appendChild(this._htmlAudioElement);
  53591. }
  53592. break;
  53593. }
  53594. }
  53595. break;
  53596. default:
  53597. validParameter = false;
  53598. break;
  53599. }
  53600. if (!validParameter) {
  53601. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53602. }
  53603. else {
  53604. if (!codecSupportedFound) {
  53605. this._isReadyToPlay = true;
  53606. // Simulating a ready to play event to avoid breaking code path
  53607. if (this._readyToPlayCallback) {
  53608. window.setTimeout(function () {
  53609. if (_this._readyToPlayCallback) {
  53610. _this._readyToPlayCallback();
  53611. }
  53612. }, 1000);
  53613. }
  53614. }
  53615. }
  53616. }
  53617. }
  53618. else {
  53619. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53620. this._scene.mainSoundTrack.AddSound(this);
  53621. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53622. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53623. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53624. }
  53625. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53626. if (this._readyToPlayCallback) {
  53627. window.setTimeout(function () {
  53628. if (_this._readyToPlayCallback) {
  53629. _this._readyToPlayCallback();
  53630. }
  53631. }, 1000);
  53632. }
  53633. }
  53634. }
  53635. Sound.prototype.dispose = function () {
  53636. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53637. if (this.isPlaying) {
  53638. this.stop();
  53639. }
  53640. this._isReadyToPlay = false;
  53641. if (this.soundTrackId === -1) {
  53642. this._scene.mainSoundTrack.RemoveSound(this);
  53643. }
  53644. else {
  53645. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53646. }
  53647. if (this._soundGain) {
  53648. this._soundGain.disconnect();
  53649. this._soundGain = null;
  53650. }
  53651. if (this._soundPanner) {
  53652. this._soundPanner.disconnect();
  53653. this._soundPanner = null;
  53654. }
  53655. if (this._soundSource) {
  53656. this._soundSource.disconnect();
  53657. this._soundSource = null;
  53658. }
  53659. this._audioBuffer = null;
  53660. if (this._htmlAudioElement) {
  53661. this._htmlAudioElement.pause();
  53662. this._htmlAudioElement.src = "";
  53663. document.body.removeChild(this._htmlAudioElement);
  53664. }
  53665. if (this._connectedMesh && this._registerFunc) {
  53666. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53667. this._connectedMesh = null;
  53668. }
  53669. }
  53670. };
  53671. Sound.prototype.isReady = function () {
  53672. return this._isReadyToPlay;
  53673. };
  53674. Sound.prototype._soundLoaded = function (audioData) {
  53675. var _this = this;
  53676. if (!BABYLON.Engine.audioEngine.audioContext) {
  53677. return;
  53678. }
  53679. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53680. _this._audioBuffer = buffer;
  53681. _this._isReadyToPlay = true;
  53682. if (_this.autoplay) {
  53683. _this.play();
  53684. }
  53685. if (_this._readyToPlayCallback) {
  53686. _this._readyToPlayCallback();
  53687. }
  53688. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53689. };
  53690. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53691. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53692. this._audioBuffer = audioBuffer;
  53693. this._isReadyToPlay = true;
  53694. }
  53695. };
  53696. Sound.prototype.updateOptions = function (options) {
  53697. if (options) {
  53698. this.loop = options.loop || this.loop;
  53699. this.maxDistance = options.maxDistance || this.maxDistance;
  53700. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53701. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53702. this.refDistance = options.refDistance || this.refDistance;
  53703. this.distanceModel = options.distanceModel || this.distanceModel;
  53704. this._playbackRate = options.playbackRate || this._playbackRate;
  53705. this._updateSpatialParameters();
  53706. if (this.isPlaying) {
  53707. if (this._streaming) {
  53708. this._htmlAudioElement.playbackRate = this._playbackRate;
  53709. }
  53710. else {
  53711. if (this._soundSource) {
  53712. this._soundSource.playbackRate.value = this._playbackRate;
  53713. }
  53714. }
  53715. }
  53716. }
  53717. };
  53718. Sound.prototype._createSpatialParameters = function () {
  53719. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53720. if (this._scene.headphone) {
  53721. this._panningModel = "HRTF";
  53722. }
  53723. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53724. this._updateSpatialParameters();
  53725. this._soundPanner.connect(this._ouputAudioNode);
  53726. this._inputAudioNode = this._soundPanner;
  53727. }
  53728. };
  53729. Sound.prototype._updateSpatialParameters = function () {
  53730. if (this.spatialSound && this._soundPanner) {
  53731. if (this.useCustomAttenuation) {
  53732. // Tricks to disable in a way embedded Web Audio attenuation
  53733. this._soundPanner.distanceModel = "linear";
  53734. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53735. this._soundPanner.refDistance = 1;
  53736. this._soundPanner.rolloffFactor = 1;
  53737. this._soundPanner.panningModel = this._panningModel;
  53738. }
  53739. else {
  53740. this._soundPanner.distanceModel = this.distanceModel;
  53741. this._soundPanner.maxDistance = this.maxDistance;
  53742. this._soundPanner.refDistance = this.refDistance;
  53743. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53744. this._soundPanner.panningModel = this._panningModel;
  53745. }
  53746. }
  53747. };
  53748. Sound.prototype.switchPanningModelToHRTF = function () {
  53749. this._panningModel = "HRTF";
  53750. this._switchPanningModel();
  53751. };
  53752. Sound.prototype.switchPanningModelToEqualPower = function () {
  53753. this._panningModel = "equalpower";
  53754. this._switchPanningModel();
  53755. };
  53756. Sound.prototype._switchPanningModel = function () {
  53757. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53758. this._soundPanner.panningModel = this._panningModel;
  53759. }
  53760. };
  53761. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53762. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53763. if (this._isOutputConnected) {
  53764. this._ouputAudioNode.disconnect();
  53765. }
  53766. this._ouputAudioNode.connect(soundTrackAudioNode);
  53767. this._isOutputConnected = true;
  53768. }
  53769. };
  53770. /**
  53771. * Transform this sound into a directional source
  53772. * @param coneInnerAngle Size of the inner cone in degree
  53773. * @param coneOuterAngle Size of the outer cone in degree
  53774. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53775. */
  53776. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53777. if (coneOuterAngle < coneInnerAngle) {
  53778. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53779. return;
  53780. }
  53781. this._coneInnerAngle = coneInnerAngle;
  53782. this._coneOuterAngle = coneOuterAngle;
  53783. this._coneOuterGain = coneOuterGain;
  53784. this._isDirectional = true;
  53785. if (this.isPlaying && this.loop) {
  53786. this.stop();
  53787. this.play();
  53788. }
  53789. };
  53790. Sound.prototype.setPosition = function (newPosition) {
  53791. this._position = newPosition;
  53792. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53793. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53794. }
  53795. };
  53796. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53797. this._localDirection = newLocalDirection;
  53798. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53799. this._updateDirection();
  53800. }
  53801. };
  53802. Sound.prototype._updateDirection = function () {
  53803. if (!this._connectedMesh || !this._soundPanner) {
  53804. return;
  53805. }
  53806. var mat = this._connectedMesh.getWorldMatrix();
  53807. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53808. direction.normalize();
  53809. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53810. };
  53811. Sound.prototype.updateDistanceFromListener = function () {
  53812. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53813. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53814. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53815. }
  53816. };
  53817. Sound.prototype.setAttenuationFunction = function (callback) {
  53818. this._customAttenuationFunction = callback;
  53819. };
  53820. /**
  53821. * Play the sound
  53822. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53823. * @param offset (optional) Start the sound setting it at a specific time
  53824. */
  53825. Sound.prototype.play = function (time, offset) {
  53826. var _this = this;
  53827. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53828. try {
  53829. if (this._startOffset < 0) {
  53830. time = -this._startOffset;
  53831. this._startOffset = 0;
  53832. }
  53833. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53834. if (!this._soundSource || !this._streamingSource) {
  53835. if (this.spatialSound && this._soundPanner) {
  53836. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53837. if (this._isDirectional) {
  53838. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53839. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53840. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53841. if (this._connectedMesh) {
  53842. this._updateDirection();
  53843. }
  53844. else {
  53845. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53846. }
  53847. }
  53848. }
  53849. }
  53850. if (this._streaming) {
  53851. if (!this._streamingSource) {
  53852. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53853. this._htmlAudioElement.onended = function () { _this._onended(); };
  53854. this._htmlAudioElement.playbackRate = this._playbackRate;
  53855. }
  53856. this._streamingSource.disconnect();
  53857. this._streamingSource.connect(this._inputAudioNode);
  53858. this._htmlAudioElement.play();
  53859. }
  53860. else {
  53861. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53862. this._soundSource.buffer = this._audioBuffer;
  53863. this._soundSource.connect(this._inputAudioNode);
  53864. this._soundSource.loop = this.loop;
  53865. this._soundSource.playbackRate.value = this._playbackRate;
  53866. this._soundSource.onended = function () { _this._onended(); };
  53867. if (this._soundSource.buffer) {
  53868. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53869. }
  53870. }
  53871. this._startTime = startTime;
  53872. this.isPlaying = true;
  53873. this.isPaused = false;
  53874. }
  53875. catch (ex) {
  53876. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53877. }
  53878. }
  53879. };
  53880. Sound.prototype._onended = function () {
  53881. this.isPlaying = false;
  53882. if (this.onended) {
  53883. this.onended();
  53884. }
  53885. };
  53886. /**
  53887. * Stop the sound
  53888. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53889. */
  53890. Sound.prototype.stop = function (time) {
  53891. if (this.isPlaying) {
  53892. if (this._streaming) {
  53893. this._htmlAudioElement.pause();
  53894. // Test needed for Firefox or it will generate an Invalid State Error
  53895. if (this._htmlAudioElement.currentTime > 0) {
  53896. this._htmlAudioElement.currentTime = 0;
  53897. }
  53898. }
  53899. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53900. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53901. this._soundSource.stop(stopTime);
  53902. this._soundSource.onended = function () { };
  53903. if (!this.isPaused) {
  53904. this._startOffset = 0;
  53905. }
  53906. }
  53907. this.isPlaying = false;
  53908. }
  53909. };
  53910. Sound.prototype.pause = function () {
  53911. if (this.isPlaying) {
  53912. this.isPaused = true;
  53913. if (this._streaming) {
  53914. this._htmlAudioElement.pause();
  53915. }
  53916. else if (BABYLON.Engine.audioEngine.audioContext) {
  53917. this.stop(0);
  53918. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53919. }
  53920. }
  53921. };
  53922. Sound.prototype.setVolume = function (newVolume, time) {
  53923. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53924. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53925. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53926. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53927. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53928. }
  53929. else {
  53930. this._soundGain.gain.value = newVolume;
  53931. }
  53932. }
  53933. this._volume = newVolume;
  53934. };
  53935. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53936. this._playbackRate = newPlaybackRate;
  53937. if (this.isPlaying) {
  53938. if (this._streaming) {
  53939. this._htmlAudioElement.playbackRate = this._playbackRate;
  53940. }
  53941. else if (this._soundSource) {
  53942. this._soundSource.playbackRate.value = this._playbackRate;
  53943. }
  53944. }
  53945. };
  53946. Sound.prototype.getVolume = function () {
  53947. return this._volume;
  53948. };
  53949. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53950. var _this = this;
  53951. if (this._connectedMesh && this._registerFunc) {
  53952. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53953. this._registerFunc = null;
  53954. }
  53955. this._connectedMesh = meshToConnectTo;
  53956. if (!this.spatialSound) {
  53957. this.spatialSound = true;
  53958. this._createSpatialParameters();
  53959. if (this.isPlaying && this.loop) {
  53960. this.stop();
  53961. this.play();
  53962. }
  53963. }
  53964. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53965. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53966. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53967. };
  53968. Sound.prototype.detachFromMesh = function () {
  53969. if (this._connectedMesh && this._registerFunc) {
  53970. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53971. this._registerFunc = null;
  53972. this._connectedMesh = null;
  53973. }
  53974. };
  53975. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53976. if (!node.getBoundingInfo) {
  53977. return;
  53978. }
  53979. var mesh = node;
  53980. var boundingInfo = mesh.getBoundingInfo();
  53981. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53982. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53983. this._updateDirection();
  53984. }
  53985. };
  53986. Sound.prototype.clone = function () {
  53987. var _this = this;
  53988. if (!this._streaming) {
  53989. var setBufferAndRun = function () {
  53990. if (_this._isReadyToPlay) {
  53991. clonedSound._audioBuffer = _this.getAudioBuffer();
  53992. clonedSound._isReadyToPlay = true;
  53993. if (clonedSound.autoplay) {
  53994. clonedSound.play();
  53995. }
  53996. }
  53997. else {
  53998. window.setTimeout(setBufferAndRun, 300);
  53999. }
  54000. };
  54001. var currentOptions = {
  54002. autoplay: this.autoplay, loop: this.loop,
  54003. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  54004. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  54005. refDistance: this.refDistance, distanceModel: this.distanceModel
  54006. };
  54007. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  54008. if (this.useCustomAttenuation) {
  54009. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  54010. }
  54011. clonedSound.setPosition(this._position);
  54012. clonedSound.setPlaybackRate(this._playbackRate);
  54013. setBufferAndRun();
  54014. return clonedSound;
  54015. }
  54016. else {
  54017. return null;
  54018. }
  54019. };
  54020. Sound.prototype.getAudioBuffer = function () {
  54021. return this._audioBuffer;
  54022. };
  54023. Sound.prototype.serialize = function () {
  54024. var serializationObject = {
  54025. name: this.name,
  54026. url: this.name,
  54027. autoplay: this.autoplay,
  54028. loop: this.loop,
  54029. volume: this._volume,
  54030. spatialSound: this.spatialSound,
  54031. maxDistance: this.maxDistance,
  54032. rolloffFactor: this.rolloffFactor,
  54033. refDistance: this.refDistance,
  54034. distanceModel: this.distanceModel,
  54035. playbackRate: this._playbackRate,
  54036. panningModel: this._panningModel,
  54037. soundTrackId: this.soundTrackId
  54038. };
  54039. if (this.spatialSound) {
  54040. if (this._connectedMesh)
  54041. serializationObject.connectedMeshId = this._connectedMesh.id;
  54042. serializationObject.position = this._position.asArray();
  54043. serializationObject.refDistance = this.refDistance;
  54044. serializationObject.distanceModel = this.distanceModel;
  54045. serializationObject.isDirectional = this._isDirectional;
  54046. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  54047. serializationObject.coneInnerAngle = this._coneInnerAngle;
  54048. serializationObject.coneOuterAngle = this._coneOuterAngle;
  54049. serializationObject.coneOuterGain = this._coneOuterGain;
  54050. }
  54051. return serializationObject;
  54052. };
  54053. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  54054. var soundName = parsedSound.name;
  54055. var soundUrl;
  54056. if (parsedSound.url) {
  54057. soundUrl = rootUrl + parsedSound.url;
  54058. }
  54059. else {
  54060. soundUrl = rootUrl + soundName;
  54061. }
  54062. var options = {
  54063. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  54064. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  54065. rolloffFactor: parsedSound.rolloffFactor,
  54066. refDistance: parsedSound.refDistance,
  54067. distanceModel: parsedSound.distanceModel,
  54068. playbackRate: parsedSound.playbackRate
  54069. };
  54070. var newSound;
  54071. if (!sourceSound) {
  54072. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  54073. scene._addPendingData(newSound);
  54074. }
  54075. else {
  54076. var setBufferAndRun = function () {
  54077. if (sourceSound._isReadyToPlay) {
  54078. newSound._audioBuffer = sourceSound.getAudioBuffer();
  54079. newSound._isReadyToPlay = true;
  54080. if (newSound.autoplay) {
  54081. newSound.play();
  54082. }
  54083. }
  54084. else {
  54085. window.setTimeout(setBufferAndRun, 300);
  54086. }
  54087. };
  54088. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  54089. setBufferAndRun();
  54090. }
  54091. if (parsedSound.position) {
  54092. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  54093. newSound.setPosition(soundPosition);
  54094. }
  54095. if (parsedSound.isDirectional) {
  54096. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  54097. if (parsedSound.localDirectionToMesh) {
  54098. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  54099. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  54100. }
  54101. }
  54102. if (parsedSound.connectedMeshId) {
  54103. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  54104. if (connectedMesh) {
  54105. newSound.attachToMesh(connectedMesh);
  54106. }
  54107. }
  54108. return newSound;
  54109. };
  54110. return Sound;
  54111. }());
  54112. BABYLON.Sound = Sound;
  54113. })(BABYLON || (BABYLON = {}));
  54114. //# sourceMappingURL=babylon.sound.js.map
  54115. var BABYLON;
  54116. (function (BABYLON) {
  54117. var SoundTrack = /** @class */ (function () {
  54118. function SoundTrack(scene, options) {
  54119. this.id = -1;
  54120. this._isMainTrack = false;
  54121. this._isInitialized = false;
  54122. this._scene = scene;
  54123. this.soundCollection = new Array();
  54124. this._options = options;
  54125. if (!this._isMainTrack) {
  54126. this._scene.soundTracks.push(this);
  54127. this.id = this._scene.soundTracks.length - 1;
  54128. }
  54129. }
  54130. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  54131. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54132. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  54133. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  54134. if (this._options) {
  54135. if (this._options.volume) {
  54136. this._outputAudioNode.gain.value = this._options.volume;
  54137. }
  54138. if (this._options.mainTrack) {
  54139. this._isMainTrack = this._options.mainTrack;
  54140. }
  54141. }
  54142. this._isInitialized = true;
  54143. }
  54144. };
  54145. SoundTrack.prototype.dispose = function () {
  54146. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54147. if (this._connectedAnalyser) {
  54148. this._connectedAnalyser.stopDebugCanvas();
  54149. }
  54150. while (this.soundCollection.length) {
  54151. this.soundCollection[0].dispose();
  54152. }
  54153. if (this._outputAudioNode) {
  54154. this._outputAudioNode.disconnect();
  54155. }
  54156. this._outputAudioNode = null;
  54157. }
  54158. };
  54159. SoundTrack.prototype.AddSound = function (sound) {
  54160. if (!this._isInitialized) {
  54161. this._initializeSoundTrackAudioGraph();
  54162. }
  54163. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54164. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  54165. }
  54166. if (sound.soundTrackId) {
  54167. if (sound.soundTrackId === -1) {
  54168. this._scene.mainSoundTrack.RemoveSound(sound);
  54169. }
  54170. else {
  54171. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  54172. }
  54173. }
  54174. this.soundCollection.push(sound);
  54175. sound.soundTrackId = this.id;
  54176. };
  54177. SoundTrack.prototype.RemoveSound = function (sound) {
  54178. var index = this.soundCollection.indexOf(sound);
  54179. if (index !== -1) {
  54180. this.soundCollection.splice(index, 1);
  54181. }
  54182. };
  54183. SoundTrack.prototype.setVolume = function (newVolume) {
  54184. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54185. this._outputAudioNode.gain.value = newVolume;
  54186. }
  54187. };
  54188. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  54189. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54190. for (var i = 0; i < this.soundCollection.length; i++) {
  54191. this.soundCollection[i].switchPanningModelToHRTF();
  54192. }
  54193. }
  54194. };
  54195. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  54196. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54197. for (var i = 0; i < this.soundCollection.length; i++) {
  54198. this.soundCollection[i].switchPanningModelToEqualPower();
  54199. }
  54200. }
  54201. };
  54202. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  54203. if (this._connectedAnalyser) {
  54204. this._connectedAnalyser.stopDebugCanvas();
  54205. }
  54206. this._connectedAnalyser = analyser;
  54207. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54208. this._outputAudioNode.disconnect();
  54209. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  54210. }
  54211. };
  54212. return SoundTrack;
  54213. }());
  54214. BABYLON.SoundTrack = SoundTrack;
  54215. })(BABYLON || (BABYLON = {}));
  54216. //# sourceMappingURL=babylon.soundtrack.js.map
  54217. var BABYLON;
  54218. (function (BABYLON) {
  54219. var Analyser = /** @class */ (function () {
  54220. function Analyser(scene) {
  54221. this.SMOOTHING = 0.75;
  54222. this.FFT_SIZE = 512;
  54223. this.BARGRAPHAMPLITUDE = 256;
  54224. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54225. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54226. this._scene = scene;
  54227. this._audioEngine = BABYLON.Engine.audioEngine;
  54228. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  54229. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54230. this._webAudioAnalyser.minDecibels = -140;
  54231. this._webAudioAnalyser.maxDecibels = 0;
  54232. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54233. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54234. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54235. }
  54236. }
  54237. Analyser.prototype.getFrequencyBinCount = function () {
  54238. if (this._audioEngine.canUseWebAudio) {
  54239. return this._webAudioAnalyser.frequencyBinCount;
  54240. }
  54241. else {
  54242. return 0;
  54243. }
  54244. };
  54245. Analyser.prototype.getByteFrequencyData = function () {
  54246. if (this._audioEngine.canUseWebAudio) {
  54247. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54248. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54249. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54250. }
  54251. return this._byteFreqs;
  54252. };
  54253. Analyser.prototype.getByteTimeDomainData = function () {
  54254. if (this._audioEngine.canUseWebAudio) {
  54255. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54256. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54257. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54258. }
  54259. return this._byteTime;
  54260. };
  54261. Analyser.prototype.getFloatFrequencyData = function () {
  54262. if (this._audioEngine.canUseWebAudio) {
  54263. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54264. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54265. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54266. }
  54267. return this._floatFreqs;
  54268. };
  54269. Analyser.prototype.drawDebugCanvas = function () {
  54270. var _this = this;
  54271. if (this._audioEngine.canUseWebAudio) {
  54272. if (!this._debugCanvas) {
  54273. this._debugCanvas = document.createElement("canvas");
  54274. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54275. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54276. this._debugCanvas.style.position = "absolute";
  54277. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54278. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54279. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54280. document.body.appendChild(this._debugCanvas);
  54281. this._registerFunc = function () {
  54282. _this.drawDebugCanvas();
  54283. };
  54284. this._scene.registerBeforeRender(this._registerFunc);
  54285. }
  54286. if (this._registerFunc && this._debugCanvasContext) {
  54287. var workingArray = this.getByteFrequencyData();
  54288. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54289. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54290. // Draw the frequency domain chart.
  54291. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54292. var value = workingArray[i];
  54293. var percent = value / this.BARGRAPHAMPLITUDE;
  54294. var height = this.DEBUGCANVASSIZE.height * percent;
  54295. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54296. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54297. var hue = i / this.getFrequencyBinCount() * 360;
  54298. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54299. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54300. }
  54301. }
  54302. }
  54303. };
  54304. Analyser.prototype.stopDebugCanvas = function () {
  54305. if (this._debugCanvas) {
  54306. if (this._registerFunc) {
  54307. this._scene.unregisterBeforeRender(this._registerFunc);
  54308. this._registerFunc = null;
  54309. }
  54310. document.body.removeChild(this._debugCanvas);
  54311. this._debugCanvas = null;
  54312. this._debugCanvasContext = null;
  54313. }
  54314. };
  54315. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54316. if (this._audioEngine.canUseWebAudio) {
  54317. inputAudioNode.connect(this._webAudioAnalyser);
  54318. this._webAudioAnalyser.connect(outputAudioNode);
  54319. }
  54320. };
  54321. Analyser.prototype.dispose = function () {
  54322. if (this._audioEngine.canUseWebAudio) {
  54323. this._webAudioAnalyser.disconnect();
  54324. }
  54325. };
  54326. return Analyser;
  54327. }());
  54328. BABYLON.Analyser = Analyser;
  54329. })(BABYLON || (BABYLON = {}));
  54330. //# sourceMappingURL=babylon.analyser.js.map
  54331. var BABYLON;
  54332. (function (BABYLON) {
  54333. var CubeTexture = /** @class */ (function (_super) {
  54334. __extends(CubeTexture, _super);
  54335. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  54336. if (extensions === void 0) { extensions = null; }
  54337. if (noMipmap === void 0) { noMipmap = false; }
  54338. if (files === void 0) { files = null; }
  54339. if (onLoad === void 0) { onLoad = null; }
  54340. if (onError === void 0) { onError = null; }
  54341. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54342. if (prefiltered === void 0) { prefiltered = false; }
  54343. if (forcedExtension === void 0) { forcedExtension = null; }
  54344. var _this = _super.call(this, scene) || this;
  54345. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54346. _this.name = rootUrl;
  54347. _this.url = rootUrl;
  54348. _this._noMipmap = noMipmap;
  54349. _this.hasAlpha = false;
  54350. _this._format = format;
  54351. _this._prefiltered = prefiltered;
  54352. _this.isCube = true;
  54353. _this._textureMatrix = BABYLON.Matrix.Identity();
  54354. if (prefiltered) {
  54355. _this.gammaSpace = false;
  54356. }
  54357. if (!rootUrl && !files) {
  54358. return _this;
  54359. }
  54360. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  54361. var lastDot = rootUrl.lastIndexOf(".");
  54362. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  54363. var isDDS = (extension === ".dds");
  54364. if (!files) {
  54365. if (!isDDS && !extensions) {
  54366. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  54367. }
  54368. files = [];
  54369. if (extensions) {
  54370. for (var index = 0; index < extensions.length; index++) {
  54371. files.push(rootUrl + extensions[index]);
  54372. }
  54373. }
  54374. }
  54375. _this._files = files;
  54376. if (!_this._texture) {
  54377. if (!scene.useDelayedTextureLoading) {
  54378. if (prefiltered) {
  54379. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  54380. }
  54381. else {
  54382. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  54383. }
  54384. }
  54385. else {
  54386. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54387. }
  54388. }
  54389. else if (onLoad) {
  54390. if (_this._texture.isReady) {
  54391. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  54392. }
  54393. else {
  54394. _this._texture.onLoadedObservable.add(onLoad);
  54395. }
  54396. }
  54397. return _this;
  54398. }
  54399. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  54400. return new CubeTexture("", scene, null, noMipmap, files);
  54401. };
  54402. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  54403. if (forcedExtension === void 0) { forcedExtension = null; }
  54404. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  54405. };
  54406. // Methods
  54407. CubeTexture.prototype.delayLoad = function () {
  54408. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54409. return;
  54410. }
  54411. var scene = this.getScene();
  54412. if (!scene) {
  54413. return;
  54414. }
  54415. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54416. this._texture = this._getFromCache(this.url, this._noMipmap);
  54417. if (!this._texture) {
  54418. if (this._prefiltered) {
  54419. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  54420. }
  54421. else {
  54422. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  54423. }
  54424. }
  54425. };
  54426. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  54427. return this._textureMatrix;
  54428. };
  54429. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  54430. this._textureMatrix = value;
  54431. };
  54432. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54433. var texture = BABYLON.SerializationHelper.Parse(function () {
  54434. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  54435. }, parsedTexture, scene);
  54436. // Animations
  54437. if (parsedTexture.animations) {
  54438. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  54439. var parsedAnimation = parsedTexture.animations[animationIndex];
  54440. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54441. }
  54442. }
  54443. return texture;
  54444. };
  54445. CubeTexture.prototype.clone = function () {
  54446. var _this = this;
  54447. return BABYLON.SerializationHelper.Clone(function () {
  54448. var scene = _this.getScene();
  54449. if (!scene) {
  54450. return _this;
  54451. }
  54452. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  54453. }, this);
  54454. };
  54455. return CubeTexture;
  54456. }(BABYLON.BaseTexture));
  54457. BABYLON.CubeTexture = CubeTexture;
  54458. })(BABYLON || (BABYLON = {}));
  54459. //# sourceMappingURL=babylon.cubeTexture.js.map
  54460. var BABYLON;
  54461. (function (BABYLON) {
  54462. var RenderTargetTexture = /** @class */ (function (_super) {
  54463. __extends(RenderTargetTexture, _super);
  54464. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  54465. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  54466. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54467. if (isCube === void 0) { isCube = false; }
  54468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54469. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54470. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  54471. if (isMulti === void 0) { isMulti = false; }
  54472. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54473. _this.isCube = isCube;
  54474. /**
  54475. * Use this list to define the list of mesh you want to render.
  54476. */
  54477. _this.renderList = new Array();
  54478. _this.renderParticles = true;
  54479. _this.renderSprites = false;
  54480. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  54481. _this.ignoreCameraViewport = false;
  54482. // Events
  54483. /**
  54484. * An event triggered when the texture is unbind.
  54485. * @type {BABYLON.Observable}
  54486. */
  54487. _this.onBeforeBindObservable = new BABYLON.Observable();
  54488. /**
  54489. * An event triggered when the texture is unbind.
  54490. * @type {BABYLON.Observable}
  54491. */
  54492. _this.onAfterUnbindObservable = new BABYLON.Observable();
  54493. /**
  54494. * An event triggered before rendering the texture
  54495. * @type {BABYLON.Observable}
  54496. */
  54497. _this.onBeforeRenderObservable = new BABYLON.Observable();
  54498. /**
  54499. * An event triggered after rendering the texture
  54500. * @type {BABYLON.Observable}
  54501. */
  54502. _this.onAfterRenderObservable = new BABYLON.Observable();
  54503. /**
  54504. * An event triggered after the texture clear
  54505. * @type {BABYLON.Observable}
  54506. */
  54507. _this.onClearObservable = new BABYLON.Observable();
  54508. _this._currentRefreshId = -1;
  54509. _this._refreshRate = 1;
  54510. _this._samples = 1;
  54511. scene = _this.getScene();
  54512. if (!scene) {
  54513. return _this;
  54514. }
  54515. _this._engine = scene.getEngine();
  54516. _this.name = name;
  54517. _this.isRenderTarget = true;
  54518. _this._initialSizeParameter = size;
  54519. _this._processSizeParameter(size);
  54520. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  54521. });
  54522. _this._generateMipMaps = generateMipMaps ? true : false;
  54523. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  54524. // Rendering groups
  54525. _this._renderingManager = new BABYLON.RenderingManager(scene);
  54526. if (isMulti) {
  54527. return _this;
  54528. }
  54529. _this._renderTargetOptions = {
  54530. generateMipMaps: generateMipMaps,
  54531. type: type,
  54532. samplingMode: samplingMode,
  54533. generateDepthBuffer: generateDepthBuffer,
  54534. generateStencilBuffer: generateStencilBuffer
  54535. };
  54536. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  54537. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54538. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54539. }
  54540. if (isCube) {
  54541. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  54542. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  54543. _this._textureMatrix = BABYLON.Matrix.Identity();
  54544. }
  54545. else {
  54546. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  54547. }
  54548. return _this;
  54549. }
  54550. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  54551. get: function () {
  54552. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  54553. },
  54554. enumerable: true,
  54555. configurable: true
  54556. });
  54557. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54558. get: function () {
  54559. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54560. },
  54561. enumerable: true,
  54562. configurable: true
  54563. });
  54564. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54565. get: function () {
  54566. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54567. },
  54568. enumerable: true,
  54569. configurable: true
  54570. });
  54571. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54572. set: function (callback) {
  54573. if (this._onAfterUnbindObserver) {
  54574. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54575. }
  54576. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54577. },
  54578. enumerable: true,
  54579. configurable: true
  54580. });
  54581. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54582. set: function (callback) {
  54583. if (this._onBeforeRenderObserver) {
  54584. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54585. }
  54586. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54587. },
  54588. enumerable: true,
  54589. configurable: true
  54590. });
  54591. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54592. set: function (callback) {
  54593. if (this._onAfterRenderObserver) {
  54594. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54595. }
  54596. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54597. },
  54598. enumerable: true,
  54599. configurable: true
  54600. });
  54601. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54602. set: function (callback) {
  54603. if (this._onClearObserver) {
  54604. this.onClearObservable.remove(this._onClearObserver);
  54605. }
  54606. this._onClearObserver = this.onClearObservable.add(callback);
  54607. },
  54608. enumerable: true,
  54609. configurable: true
  54610. });
  54611. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54612. get: function () {
  54613. return this._renderTargetOptions;
  54614. },
  54615. enumerable: true,
  54616. configurable: true
  54617. });
  54618. RenderTargetTexture.prototype._onRatioRescale = function () {
  54619. if (this._sizeRatio) {
  54620. this.resize(this._initialSizeParameter);
  54621. }
  54622. };
  54623. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54624. if (size.ratio) {
  54625. this._sizeRatio = size.ratio;
  54626. this._size = {
  54627. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54628. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54629. };
  54630. }
  54631. else {
  54632. this._size = size;
  54633. }
  54634. };
  54635. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54636. get: function () {
  54637. return this._samples;
  54638. },
  54639. set: function (value) {
  54640. if (this._samples === value) {
  54641. return;
  54642. }
  54643. var scene = this.getScene();
  54644. if (!scene) {
  54645. return;
  54646. }
  54647. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54648. },
  54649. enumerable: true,
  54650. configurable: true
  54651. });
  54652. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54653. this._currentRefreshId = -1;
  54654. };
  54655. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54656. get: function () {
  54657. return this._refreshRate;
  54658. },
  54659. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54660. set: function (value) {
  54661. this._refreshRate = value;
  54662. this.resetRefreshCounter();
  54663. },
  54664. enumerable: true,
  54665. configurable: true
  54666. });
  54667. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54668. if (!this._postProcessManager) {
  54669. var scene = this.getScene();
  54670. if (!scene) {
  54671. return;
  54672. }
  54673. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54674. this._postProcesses = new Array();
  54675. }
  54676. this._postProcesses.push(postProcess);
  54677. this._postProcesses[0].autoClear = false;
  54678. };
  54679. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54680. if (!this._postProcesses) {
  54681. return;
  54682. }
  54683. if (dispose) {
  54684. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54685. var postProcess = _a[_i];
  54686. postProcess.dispose();
  54687. }
  54688. }
  54689. this._postProcesses = [];
  54690. };
  54691. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54692. if (!this._postProcesses) {
  54693. return;
  54694. }
  54695. var index = this._postProcesses.indexOf(postProcess);
  54696. if (index === -1) {
  54697. return;
  54698. }
  54699. this._postProcesses.splice(index, 1);
  54700. if (this._postProcesses.length > 0) {
  54701. this._postProcesses[0].autoClear = false;
  54702. }
  54703. };
  54704. RenderTargetTexture.prototype._shouldRender = function () {
  54705. if (this._currentRefreshId === -1) {
  54706. this._currentRefreshId = 1;
  54707. return true;
  54708. }
  54709. if (this.refreshRate === this._currentRefreshId) {
  54710. this._currentRefreshId = 1;
  54711. return true;
  54712. }
  54713. this._currentRefreshId++;
  54714. return false;
  54715. };
  54716. RenderTargetTexture.prototype.getRenderSize = function () {
  54717. if (this._size.width) {
  54718. return this._size.width;
  54719. }
  54720. return this._size;
  54721. };
  54722. RenderTargetTexture.prototype.getRenderWidth = function () {
  54723. if (this._size.width) {
  54724. return this._size.width;
  54725. }
  54726. return this._size;
  54727. };
  54728. RenderTargetTexture.prototype.getRenderHeight = function () {
  54729. if (this._size.width) {
  54730. return this._size.height;
  54731. }
  54732. return this._size;
  54733. };
  54734. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54735. get: function () {
  54736. return true;
  54737. },
  54738. enumerable: true,
  54739. configurable: true
  54740. });
  54741. RenderTargetTexture.prototype.scale = function (ratio) {
  54742. var newSize = this.getRenderSize() * ratio;
  54743. this.resize(newSize);
  54744. };
  54745. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54746. if (this.isCube) {
  54747. return this._textureMatrix;
  54748. }
  54749. return _super.prototype.getReflectionTextureMatrix.call(this);
  54750. };
  54751. RenderTargetTexture.prototype.resize = function (size) {
  54752. this.releaseInternalTexture();
  54753. var scene = this.getScene();
  54754. if (!scene) {
  54755. return;
  54756. }
  54757. this._processSizeParameter(size);
  54758. if (this.isCube) {
  54759. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54760. }
  54761. else {
  54762. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54763. }
  54764. };
  54765. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54766. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54767. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54768. var scene = this.getScene();
  54769. if (!scene) {
  54770. return;
  54771. }
  54772. var engine = scene.getEngine();
  54773. if (this.useCameraPostProcesses !== undefined) {
  54774. useCameraPostProcess = this.useCameraPostProcesses;
  54775. }
  54776. if (this._waitingRenderList) {
  54777. this.renderList = [];
  54778. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54779. var id = this._waitingRenderList[index];
  54780. var mesh_1 = scene.getMeshByID(id);
  54781. if (mesh_1) {
  54782. this.renderList.push(mesh_1);
  54783. }
  54784. }
  54785. delete this._waitingRenderList;
  54786. }
  54787. // Is predicate defined?
  54788. if (this.renderListPredicate) {
  54789. if (this.renderList) {
  54790. this.renderList.splice(0); // Clear previous renderList
  54791. }
  54792. else {
  54793. this.renderList = [];
  54794. }
  54795. var scene = this.getScene();
  54796. if (!scene) {
  54797. return;
  54798. }
  54799. var sceneMeshes = scene.meshes;
  54800. for (var index = 0; index < sceneMeshes.length; index++) {
  54801. var mesh = sceneMeshes[index];
  54802. if (this.renderListPredicate(mesh)) {
  54803. this.renderList.push(mesh);
  54804. }
  54805. }
  54806. }
  54807. this.onBeforeBindObservable.notifyObservers(this);
  54808. // Set custom projection.
  54809. // Needs to be before binding to prevent changing the aspect ratio.
  54810. var camera;
  54811. if (this.activeCamera) {
  54812. camera = this.activeCamera;
  54813. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54814. if (this.activeCamera !== scene.activeCamera) {
  54815. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54816. }
  54817. }
  54818. else {
  54819. camera = scene.activeCamera;
  54820. if (camera) {
  54821. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54822. }
  54823. }
  54824. // Prepare renderingManager
  54825. this._renderingManager.reset();
  54826. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54827. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54828. var sceneRenderId = scene.getRenderId();
  54829. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54830. var mesh = currentRenderList[meshIndex];
  54831. if (mesh) {
  54832. if (!mesh.isReady()) {
  54833. // Reset _currentRefreshId
  54834. this.resetRefreshCounter();
  54835. continue;
  54836. }
  54837. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54838. var isMasked = void 0;
  54839. if (!this.renderList && camera) {
  54840. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54841. }
  54842. else {
  54843. isMasked = false;
  54844. }
  54845. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54846. mesh._activate(sceneRenderId);
  54847. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54848. var subMesh = mesh.subMeshes[subIndex];
  54849. scene._activeIndices.addCount(subMesh.indexCount, false);
  54850. this._renderingManager.dispatch(subMesh, mesh);
  54851. }
  54852. }
  54853. }
  54854. }
  54855. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54856. var particleSystem = scene.particleSystems[particleIndex];
  54857. var emitter = particleSystem.emitter;
  54858. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54859. continue;
  54860. }
  54861. if (currentRenderList.indexOf(emitter) >= 0) {
  54862. this._renderingManager.dispatchParticles(particleSystem);
  54863. }
  54864. }
  54865. if (this.isCube) {
  54866. for (var face = 0; face < 6; face++) {
  54867. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54868. scene.incrementRenderId();
  54869. scene.resetCachedMaterial();
  54870. }
  54871. }
  54872. else {
  54873. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54874. }
  54875. this.onAfterUnbindObservable.notifyObservers(this);
  54876. if (scene.activeCamera) {
  54877. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54878. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54879. }
  54880. engine.setViewport(scene.activeCamera.viewport);
  54881. }
  54882. scene.resetCachedMaterial();
  54883. };
  54884. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54885. var minimum = 128;
  54886. var x = renderDimension * scale;
  54887. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54888. // Ensure we don't exceed the render dimension (while staying POT)
  54889. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54890. };
  54891. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54892. var _this = this;
  54893. if (!this._texture) {
  54894. return;
  54895. }
  54896. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54897. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54898. });
  54899. };
  54900. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54901. var scene = this.getScene();
  54902. if (!scene) {
  54903. return;
  54904. }
  54905. var engine = scene.getEngine();
  54906. if (!this._texture) {
  54907. return;
  54908. }
  54909. // Bind
  54910. if (this._postProcessManager) {
  54911. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54912. }
  54913. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54914. if (this._texture) {
  54915. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54916. }
  54917. }
  54918. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54919. // Clear
  54920. if (this.onClearObservable.hasObservers()) {
  54921. this.onClearObservable.notifyObservers(engine);
  54922. }
  54923. else {
  54924. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54925. }
  54926. if (!this._doNotChangeAspectRatio) {
  54927. scene.updateTransformMatrix(true);
  54928. }
  54929. // Render
  54930. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54931. if (this._postProcessManager) {
  54932. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54933. }
  54934. else if (useCameraPostProcess) {
  54935. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54936. }
  54937. if (!this._doNotChangeAspectRatio) {
  54938. scene.updateTransformMatrix(true);
  54939. }
  54940. // Dump ?
  54941. if (dumpForDebug) {
  54942. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54943. }
  54944. // Unbind
  54945. if (!this.isCube || faceIndex === 5) {
  54946. if (this.isCube) {
  54947. if (faceIndex === 5) {
  54948. engine.generateMipMapsForCubemap(this._texture);
  54949. }
  54950. }
  54951. this.unbindFrameBuffer(engine, faceIndex);
  54952. }
  54953. else {
  54954. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54955. }
  54956. };
  54957. /**
  54958. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54959. * This allowed control for front to back rendering or reversly depending of the special needs.
  54960. *
  54961. * @param renderingGroupId The rendering group id corresponding to its index
  54962. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54963. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54964. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54965. */
  54966. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54967. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54968. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54969. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54970. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54971. };
  54972. /**
  54973. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54974. *
  54975. * @param renderingGroupId The rendering group id corresponding to its index
  54976. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54977. */
  54978. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54979. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54980. };
  54981. RenderTargetTexture.prototype.clone = function () {
  54982. var textureSize = this.getSize();
  54983. 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);
  54984. // Base texture
  54985. newTexture.hasAlpha = this.hasAlpha;
  54986. newTexture.level = this.level;
  54987. // RenderTarget Texture
  54988. newTexture.coordinatesMode = this.coordinatesMode;
  54989. if (this.renderList) {
  54990. newTexture.renderList = this.renderList.slice(0);
  54991. }
  54992. return newTexture;
  54993. };
  54994. RenderTargetTexture.prototype.serialize = function () {
  54995. if (!this.name) {
  54996. return null;
  54997. }
  54998. var serializationObject = _super.prototype.serialize.call(this);
  54999. serializationObject.renderTargetSize = this.getRenderSize();
  55000. serializationObject.renderList = [];
  55001. if (this.renderList) {
  55002. for (var index = 0; index < this.renderList.length; index++) {
  55003. serializationObject.renderList.push(this.renderList[index].id);
  55004. }
  55005. }
  55006. return serializationObject;
  55007. };
  55008. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  55009. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  55010. var objBuffer = this.getInternalTexture();
  55011. var scene = this.getScene();
  55012. if (objBuffer && scene) {
  55013. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  55014. }
  55015. };
  55016. RenderTargetTexture.prototype.dispose = function () {
  55017. if (this._postProcessManager) {
  55018. this._postProcessManager.dispose();
  55019. this._postProcessManager = null;
  55020. }
  55021. this.clearPostProcesses(true);
  55022. if (this._resizeObserver) {
  55023. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  55024. this._resizeObserver = null;
  55025. }
  55026. this.renderList = null;
  55027. // Remove from custom render targets
  55028. var scene = this.getScene();
  55029. if (!scene) {
  55030. return;
  55031. }
  55032. var index = scene.customRenderTargets.indexOf(this);
  55033. if (index >= 0) {
  55034. scene.customRenderTargets.splice(index, 1);
  55035. }
  55036. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  55037. var camera = _a[_i];
  55038. index = camera.customRenderTargets.indexOf(this);
  55039. if (index >= 0) {
  55040. camera.customRenderTargets.splice(index, 1);
  55041. }
  55042. }
  55043. _super.prototype.dispose.call(this);
  55044. };
  55045. RenderTargetTexture.prototype._rebuild = function () {
  55046. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55047. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55048. }
  55049. if (this._postProcessManager) {
  55050. this._postProcessManager._rebuild();
  55051. }
  55052. };
  55053. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  55054. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  55055. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  55056. return RenderTargetTexture;
  55057. }(BABYLON.Texture));
  55058. BABYLON.RenderTargetTexture = RenderTargetTexture;
  55059. })(BABYLON || (BABYLON = {}));
  55060. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  55061. var BABYLON;
  55062. (function (BABYLON) {
  55063. ;
  55064. var MultiRenderTarget = /** @class */ (function (_super) {
  55065. __extends(MultiRenderTarget, _super);
  55066. function MultiRenderTarget(name, size, count, scene, options) {
  55067. var _this = this;
  55068. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  55069. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  55070. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  55071. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  55072. _this._engine = scene.getEngine();
  55073. if (!_this.isSupported) {
  55074. _this.dispose();
  55075. return;
  55076. }
  55077. var types = [];
  55078. var samplingModes = [];
  55079. for (var i = 0; i < count; i++) {
  55080. if (options && options.types && options.types[i] !== undefined) {
  55081. types.push(options.types[i]);
  55082. }
  55083. else {
  55084. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55085. }
  55086. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  55087. samplingModes.push(options.samplingModes[i]);
  55088. }
  55089. else {
  55090. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55091. }
  55092. }
  55093. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  55094. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  55095. _this._size = size;
  55096. _this._multiRenderTargetOptions = {
  55097. samplingModes: samplingModes,
  55098. generateMipMaps: generateMipMaps,
  55099. generateDepthBuffer: generateDepthBuffer,
  55100. generateStencilBuffer: generateStencilBuffer,
  55101. generateDepthTexture: generateDepthTexture,
  55102. types: types,
  55103. textureCount: count
  55104. };
  55105. _this._createInternalTextures();
  55106. _this._createTextures();
  55107. return _this;
  55108. }
  55109. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  55110. get: function () {
  55111. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  55112. },
  55113. enumerable: true,
  55114. configurable: true
  55115. });
  55116. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  55117. get: function () {
  55118. return this._textures;
  55119. },
  55120. enumerable: true,
  55121. configurable: true
  55122. });
  55123. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  55124. get: function () {
  55125. return this._textures[this._textures.length - 1];
  55126. },
  55127. enumerable: true,
  55128. configurable: true
  55129. });
  55130. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  55131. set: function (wrap) {
  55132. if (this._textures) {
  55133. for (var i = 0; i < this._textures.length; i++) {
  55134. this._textures[i].wrapU = wrap;
  55135. }
  55136. }
  55137. },
  55138. enumerable: true,
  55139. configurable: true
  55140. });
  55141. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  55142. set: function (wrap) {
  55143. if (this._textures) {
  55144. for (var i = 0; i < this._textures.length; i++) {
  55145. this._textures[i].wrapV = wrap;
  55146. }
  55147. }
  55148. },
  55149. enumerable: true,
  55150. configurable: true
  55151. });
  55152. MultiRenderTarget.prototype._rebuild = function () {
  55153. this.releaseInternalTextures();
  55154. this._createInternalTextures();
  55155. for (var i = 0; i < this._internalTextures.length; i++) {
  55156. var texture = this._textures[i];
  55157. texture._texture = this._internalTextures[i];
  55158. }
  55159. // Keeps references to frame buffer and stencil/depth buffer
  55160. this._texture = this._internalTextures[0];
  55161. };
  55162. MultiRenderTarget.prototype._createInternalTextures = function () {
  55163. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  55164. };
  55165. MultiRenderTarget.prototype._createTextures = function () {
  55166. this._textures = [];
  55167. for (var i = 0; i < this._internalTextures.length; i++) {
  55168. var texture = new BABYLON.Texture(null, this.getScene());
  55169. texture._texture = this._internalTextures[i];
  55170. this._textures.push(texture);
  55171. }
  55172. // Keeps references to frame buffer and stencil/depth buffer
  55173. this._texture = this._internalTextures[0];
  55174. };
  55175. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  55176. get: function () {
  55177. return this._samples;
  55178. },
  55179. set: function (value) {
  55180. if (this._samples === value) {
  55181. return;
  55182. }
  55183. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  55184. },
  55185. enumerable: true,
  55186. configurable: true
  55187. });
  55188. MultiRenderTarget.prototype.resize = function (size) {
  55189. this.releaseInternalTextures();
  55190. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  55191. this._createInternalTextures();
  55192. };
  55193. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  55194. var _this = this;
  55195. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  55196. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  55197. });
  55198. };
  55199. MultiRenderTarget.prototype.dispose = function () {
  55200. this.releaseInternalTextures();
  55201. _super.prototype.dispose.call(this);
  55202. };
  55203. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  55204. if (!this._internalTextures) {
  55205. return;
  55206. }
  55207. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  55208. if (this._internalTextures[i] !== undefined) {
  55209. this._internalTextures[i].dispose();
  55210. this._internalTextures.splice(i, 1);
  55211. }
  55212. }
  55213. };
  55214. return MultiRenderTarget;
  55215. }(BABYLON.RenderTargetTexture));
  55216. BABYLON.MultiRenderTarget = MultiRenderTarget;
  55217. })(BABYLON || (BABYLON = {}));
  55218. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  55219. var BABYLON;
  55220. (function (BABYLON) {
  55221. var MirrorTexture = /** @class */ (function (_super) {
  55222. __extends(MirrorTexture, _super);
  55223. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  55224. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55226. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55227. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  55228. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  55229. _this._transformMatrix = BABYLON.Matrix.Zero();
  55230. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  55231. _this._adaptiveBlurKernel = 0;
  55232. _this._blurKernelX = 0;
  55233. _this._blurKernelY = 0;
  55234. _this._blurRatio = 1.0;
  55235. _this.ignoreCameraViewport = true;
  55236. _this.onBeforeRenderObservable.add(function () {
  55237. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  55238. _this._savedViewMatrix = scene.getViewMatrix();
  55239. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  55240. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  55241. scene.clipPlane = _this.mirrorPlane;
  55242. scene.getEngine().cullBackFaces = false;
  55243. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  55244. });
  55245. _this.onAfterRenderObservable.add(function () {
  55246. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  55247. scene.getEngine().cullBackFaces = true;
  55248. scene._mirroredCameraPosition = null;
  55249. delete scene.clipPlane;
  55250. });
  55251. return _this;
  55252. }
  55253. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  55254. get: function () {
  55255. return this._blurRatio;
  55256. },
  55257. set: function (value) {
  55258. if (this._blurRatio === value) {
  55259. return;
  55260. }
  55261. this._blurRatio = value;
  55262. this._preparePostProcesses();
  55263. },
  55264. enumerable: true,
  55265. configurable: true
  55266. });
  55267. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  55268. set: function (value) {
  55269. this._adaptiveBlurKernel = value;
  55270. this._autoComputeBlurKernel();
  55271. },
  55272. enumerable: true,
  55273. configurable: true
  55274. });
  55275. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  55276. set: function (value) {
  55277. this.blurKernelX = value;
  55278. this.blurKernelY = value;
  55279. },
  55280. enumerable: true,
  55281. configurable: true
  55282. });
  55283. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  55284. get: function () {
  55285. return this._blurKernelX;
  55286. },
  55287. set: function (value) {
  55288. if (this._blurKernelX === value) {
  55289. return;
  55290. }
  55291. this._blurKernelX = value;
  55292. this._preparePostProcesses();
  55293. },
  55294. enumerable: true,
  55295. configurable: true
  55296. });
  55297. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  55298. get: function () {
  55299. return this._blurKernelY;
  55300. },
  55301. set: function (value) {
  55302. if (this._blurKernelY === value) {
  55303. return;
  55304. }
  55305. this._blurKernelY = value;
  55306. this._preparePostProcesses();
  55307. },
  55308. enumerable: true,
  55309. configurable: true
  55310. });
  55311. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  55312. var engine = this.getScene().getEngine();
  55313. var dw = this.getRenderWidth() / engine.getRenderWidth();
  55314. var dh = this.getRenderHeight() / engine.getRenderHeight();
  55315. this.blurKernelX = this._adaptiveBlurKernel * dw;
  55316. this.blurKernelY = this._adaptiveBlurKernel * dh;
  55317. };
  55318. MirrorTexture.prototype._onRatioRescale = function () {
  55319. if (this._sizeRatio) {
  55320. this.resize(this._initialSizeParameter);
  55321. if (!this._adaptiveBlurKernel) {
  55322. this._preparePostProcesses();
  55323. }
  55324. }
  55325. if (this._adaptiveBlurKernel) {
  55326. this._autoComputeBlurKernel();
  55327. }
  55328. };
  55329. MirrorTexture.prototype._preparePostProcesses = function () {
  55330. this.clearPostProcesses(true);
  55331. if (this._blurKernelX && this._blurKernelY) {
  55332. var engine = this.getScene().getEngine();
  55333. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55334. 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);
  55335. this._blurX.autoClear = false;
  55336. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  55337. this._blurX.outputTexture = this._texture;
  55338. }
  55339. else {
  55340. this._blurX.alwaysForcePOT = true;
  55341. }
  55342. 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);
  55343. this._blurY.autoClear = false;
  55344. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  55345. this.addPostProcess(this._blurX);
  55346. this.addPostProcess(this._blurY);
  55347. }
  55348. else {
  55349. if (this._blurY) {
  55350. this.removePostProcess(this._blurY);
  55351. this._blurY.dispose();
  55352. this._blurY = null;
  55353. }
  55354. if (this._blurX) {
  55355. this.removePostProcess(this._blurX);
  55356. this._blurX.dispose();
  55357. this._blurX = null;
  55358. }
  55359. }
  55360. };
  55361. MirrorTexture.prototype.clone = function () {
  55362. var scene = this.getScene();
  55363. if (!scene) {
  55364. return this;
  55365. }
  55366. var textureSize = this.getSize();
  55367. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  55368. // Base texture
  55369. newTexture.hasAlpha = this.hasAlpha;
  55370. newTexture.level = this.level;
  55371. // Mirror Texture
  55372. newTexture.mirrorPlane = this.mirrorPlane.clone();
  55373. if (this.renderList) {
  55374. newTexture.renderList = this.renderList.slice(0);
  55375. }
  55376. return newTexture;
  55377. };
  55378. MirrorTexture.prototype.serialize = function () {
  55379. if (!this.name) {
  55380. return null;
  55381. }
  55382. var serializationObject = _super.prototype.serialize.call(this);
  55383. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  55384. return serializationObject;
  55385. };
  55386. return MirrorTexture;
  55387. }(BABYLON.RenderTargetTexture));
  55388. BABYLON.MirrorTexture = MirrorTexture;
  55389. })(BABYLON || (BABYLON = {}));
  55390. //# sourceMappingURL=babylon.mirrorTexture.js.map
  55391. var BABYLON;
  55392. (function (BABYLON) {
  55393. /**
  55394. * Creates a refraction texture used by refraction channel of the standard material.
  55395. * @param name the texture name
  55396. * @param size size of the underlying texture
  55397. * @param scene root scene
  55398. */
  55399. var RefractionTexture = /** @class */ (function (_super) {
  55400. __extends(RefractionTexture, _super);
  55401. function RefractionTexture(name, size, scene, generateMipMaps) {
  55402. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  55403. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  55404. _this.depth = 2.0;
  55405. _this.onBeforeRenderObservable.add(function () {
  55406. scene.clipPlane = _this.refractionPlane;
  55407. });
  55408. _this.onAfterRenderObservable.add(function () {
  55409. delete scene.clipPlane;
  55410. });
  55411. return _this;
  55412. }
  55413. RefractionTexture.prototype.clone = function () {
  55414. var scene = this.getScene();
  55415. if (!scene) {
  55416. return this;
  55417. }
  55418. var textureSize = this.getSize();
  55419. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  55420. // Base texture
  55421. newTexture.hasAlpha = this.hasAlpha;
  55422. newTexture.level = this.level;
  55423. // Refraction Texture
  55424. newTexture.refractionPlane = this.refractionPlane.clone();
  55425. if (this.renderList) {
  55426. newTexture.renderList = this.renderList.slice(0);
  55427. }
  55428. newTexture.depth = this.depth;
  55429. return newTexture;
  55430. };
  55431. RefractionTexture.prototype.serialize = function () {
  55432. if (!this.name) {
  55433. return null;
  55434. }
  55435. var serializationObject = _super.prototype.serialize.call(this);
  55436. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  55437. serializationObject.depth = this.depth;
  55438. return serializationObject;
  55439. };
  55440. return RefractionTexture;
  55441. }(BABYLON.RenderTargetTexture));
  55442. BABYLON.RefractionTexture = RefractionTexture;
  55443. })(BABYLON || (BABYLON = {}));
  55444. //# sourceMappingURL=babylon.refractionTexture.js.map
  55445. var BABYLON;
  55446. (function (BABYLON) {
  55447. var DynamicTexture = /** @class */ (function (_super) {
  55448. __extends(DynamicTexture, _super);
  55449. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  55450. if (scene === void 0) { scene = null; }
  55451. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55452. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55453. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  55454. _this.name = name;
  55455. _this._engine = _this.getScene().getEngine();
  55456. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55457. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55458. _this._generateMipMaps = generateMipMaps;
  55459. if (options.getContext) {
  55460. _this._canvas = options;
  55461. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55462. }
  55463. else {
  55464. _this._canvas = document.createElement("canvas");
  55465. if (options.width) {
  55466. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55467. }
  55468. else {
  55469. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  55470. }
  55471. }
  55472. var textureSize = _this.getSize();
  55473. _this._canvas.width = textureSize.width;
  55474. _this._canvas.height = textureSize.height;
  55475. _this._context = _this._canvas.getContext("2d");
  55476. return _this;
  55477. }
  55478. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  55479. get: function () {
  55480. return true;
  55481. },
  55482. enumerable: true,
  55483. configurable: true
  55484. });
  55485. DynamicTexture.prototype._recreate = function (textureSize) {
  55486. this._canvas.width = textureSize.width;
  55487. this._canvas.height = textureSize.height;
  55488. this.releaseInternalTexture();
  55489. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  55490. };
  55491. DynamicTexture.prototype.scale = function (ratio) {
  55492. var textureSize = this.getSize();
  55493. textureSize.width *= ratio;
  55494. textureSize.height *= ratio;
  55495. this._recreate(textureSize);
  55496. };
  55497. DynamicTexture.prototype.scaleTo = function (width, height) {
  55498. var textureSize = this.getSize();
  55499. textureSize.width = width;
  55500. textureSize.height = height;
  55501. this._recreate(textureSize);
  55502. };
  55503. DynamicTexture.prototype.getContext = function () {
  55504. return this._context;
  55505. };
  55506. DynamicTexture.prototype.clear = function () {
  55507. var size = this.getSize();
  55508. this._context.fillRect(0, 0, size.width, size.height);
  55509. };
  55510. DynamicTexture.prototype.update = function (invertY) {
  55511. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  55512. };
  55513. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  55514. if (update === void 0) { update = true; }
  55515. var size = this.getSize();
  55516. if (clearColor) {
  55517. this._context.fillStyle = clearColor;
  55518. this._context.fillRect(0, 0, size.width, size.height);
  55519. }
  55520. this._context.font = font;
  55521. if (x === null || x === undefined) {
  55522. var textSize = this._context.measureText(text);
  55523. x = (size.width - textSize.width) / 2;
  55524. }
  55525. if (y === null || y === undefined) {
  55526. var fontSize = parseInt((font.replace(/\D/g, '')));
  55527. ;
  55528. y = (size.height / 2) + (fontSize / 3.65);
  55529. }
  55530. this._context.fillStyle = color;
  55531. this._context.fillText(text, x, y);
  55532. if (update) {
  55533. this.update(invertY);
  55534. }
  55535. };
  55536. DynamicTexture.prototype.clone = function () {
  55537. var scene = this.getScene();
  55538. if (!scene) {
  55539. return this;
  55540. }
  55541. var textureSize = this.getSize();
  55542. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  55543. // Base texture
  55544. newTexture.hasAlpha = this.hasAlpha;
  55545. newTexture.level = this.level;
  55546. // Dynamic Texture
  55547. newTexture.wrapU = this.wrapU;
  55548. newTexture.wrapV = this.wrapV;
  55549. return newTexture;
  55550. };
  55551. DynamicTexture.prototype._rebuild = function () {
  55552. this.update();
  55553. };
  55554. return DynamicTexture;
  55555. }(BABYLON.Texture));
  55556. BABYLON.DynamicTexture = DynamicTexture;
  55557. })(BABYLON || (BABYLON = {}));
  55558. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55559. var BABYLON;
  55560. (function (BABYLON) {
  55561. var VideoTexture = /** @class */ (function (_super) {
  55562. __extends(VideoTexture, _super);
  55563. /**
  55564. * Creates a video texture.
  55565. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55566. * @param {string | null} name optional name, will detect from video source, if not defined
  55567. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55568. * @param {BABYLON.Scene} scene is obviously the current scene.
  55569. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55570. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55571. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55572. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55573. */
  55574. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55575. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55576. if (invertY === void 0) { invertY = false; }
  55577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55578. if (settings === void 0) { settings = {
  55579. autoPlay: true,
  55580. loop: true,
  55581. autoUpdateTexture: true,
  55582. }; }
  55583. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55584. _this._createInternalTexture = function () {
  55585. if (_this._texture != null) {
  55586. return;
  55587. }
  55588. if (!_this._engine.needPOTTextures ||
  55589. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55590. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55591. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55592. }
  55593. else {
  55594. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55595. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55596. _this._generateMipMaps = false;
  55597. }
  55598. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55599. _this._texture.isReady = true;
  55600. _this._updateInternalTexture();
  55601. };
  55602. _this.reset = function () {
  55603. if (_this._texture == null) {
  55604. return;
  55605. }
  55606. _this._texture.dispose();
  55607. _this._texture = null;
  55608. };
  55609. _this._updateInternalTexture = function (e) {
  55610. if (_this._texture == null || !_this._texture.isReady) {
  55611. return;
  55612. }
  55613. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55614. return;
  55615. }
  55616. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55617. };
  55618. _this._engine = _this.getScene().getEngine();
  55619. _this._generateMipMaps = generateMipMaps;
  55620. _this._samplingMode = samplingMode;
  55621. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55622. _this.name = name || _this._getName(src);
  55623. _this.video = _this._getVideo(src);
  55624. if (settings.autoPlay !== undefined) {
  55625. _this.video.autoplay = settings.autoPlay;
  55626. }
  55627. if (settings.loop !== undefined) {
  55628. _this.video.loop = settings.loop;
  55629. }
  55630. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55631. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55632. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55633. _this.video.addEventListener("emptied", _this.reset);
  55634. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55635. _this._createInternalTexture();
  55636. }
  55637. return _this;
  55638. }
  55639. VideoTexture.prototype._getName = function (src) {
  55640. if (src instanceof HTMLVideoElement) {
  55641. return src.currentSrc;
  55642. }
  55643. if (typeof src === "object") {
  55644. return src.toString();
  55645. }
  55646. return src;
  55647. };
  55648. ;
  55649. VideoTexture.prototype._getVideo = function (src) {
  55650. if (src instanceof HTMLVideoElement) {
  55651. return src;
  55652. }
  55653. var video = document.createElement("video");
  55654. if (typeof src === "string") {
  55655. video.src = src;
  55656. }
  55657. else {
  55658. src.forEach(function (url) {
  55659. var source = document.createElement("source");
  55660. source.src = url;
  55661. video.appendChild(source);
  55662. });
  55663. }
  55664. return video;
  55665. };
  55666. ;
  55667. /**
  55668. * Internal method to initiate `update`.
  55669. */
  55670. VideoTexture.prototype._rebuild = function () {
  55671. this.update();
  55672. };
  55673. /**
  55674. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55675. */
  55676. VideoTexture.prototype.update = function () {
  55677. if (!this.autoUpdateTexture) {
  55678. // Expecting user to call `updateTexture` manually
  55679. return;
  55680. }
  55681. this.updateTexture(true);
  55682. };
  55683. /**
  55684. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55685. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55686. */
  55687. VideoTexture.prototype.updateTexture = function (isVisible) {
  55688. if (!isVisible) {
  55689. return;
  55690. }
  55691. if (this.video.paused) {
  55692. return;
  55693. }
  55694. this._updateInternalTexture();
  55695. };
  55696. /**
  55697. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55698. * @param url New url.
  55699. */
  55700. VideoTexture.prototype.updateURL = function (url) {
  55701. this.video.src = url;
  55702. };
  55703. VideoTexture.prototype.dispose = function () {
  55704. _super.prototype.dispose.call(this);
  55705. this.video.removeEventListener("canplay", this._createInternalTexture);
  55706. this.video.removeEventListener("paused", this._updateInternalTexture);
  55707. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55708. this.video.removeEventListener("emptied", this.reset);
  55709. };
  55710. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55711. var video = document.createElement("video");
  55712. var constraintsDeviceId;
  55713. if (constraints && constraints.deviceId) {
  55714. constraintsDeviceId = {
  55715. exact: constraints.deviceId,
  55716. };
  55717. }
  55718. navigator.getUserMedia =
  55719. navigator.getUserMedia ||
  55720. navigator.webkitGetUserMedia ||
  55721. navigator.mozGetUserMedia ||
  55722. navigator.msGetUserMedia;
  55723. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55724. if (navigator.getUserMedia) {
  55725. navigator.getUserMedia({
  55726. video: {
  55727. deviceId: constraintsDeviceId,
  55728. width: {
  55729. min: (constraints && constraints.minWidth) || 256,
  55730. max: (constraints && constraints.maxWidth) || 640,
  55731. },
  55732. height: {
  55733. min: (constraints && constraints.minHeight) || 256,
  55734. max: (constraints && constraints.maxHeight) || 480,
  55735. },
  55736. },
  55737. }, function (stream) {
  55738. if (video.mozSrcObject !== undefined) {
  55739. // hack for Firefox < 19
  55740. video.mozSrcObject = stream;
  55741. }
  55742. else {
  55743. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55744. }
  55745. video.play();
  55746. if (onReady) {
  55747. onReady(new VideoTexture("video", video, scene, true, true));
  55748. }
  55749. }, function (e) {
  55750. BABYLON.Tools.Error(e.name);
  55751. });
  55752. }
  55753. };
  55754. return VideoTexture;
  55755. }(BABYLON.Texture));
  55756. BABYLON.VideoTexture = VideoTexture;
  55757. })(BABYLON || (BABYLON = {}));
  55758. //# sourceMappingURL=babylon.videoTexture.js.map
  55759. var BABYLON;
  55760. (function (BABYLON) {
  55761. var RawTexture = /** @class */ (function (_super) {
  55762. __extends(RawTexture, _super);
  55763. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55764. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55765. if (invertY === void 0) { invertY = false; }
  55766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55767. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55768. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55769. _this.format = format;
  55770. _this._engine = scene.getEngine();
  55771. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55772. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55773. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55774. return _this;
  55775. }
  55776. RawTexture.prototype.update = function (data) {
  55777. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55778. };
  55779. // Statics
  55780. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55781. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55782. if (invertY === void 0) { invertY = false; }
  55783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55784. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55785. };
  55786. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55787. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55788. if (invertY === void 0) { invertY = false; }
  55789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55790. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55791. };
  55792. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55793. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55794. if (invertY === void 0) { invertY = false; }
  55795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55796. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55797. };
  55798. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55799. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55800. if (invertY === void 0) { invertY = false; }
  55801. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55802. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55803. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55804. };
  55805. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55806. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55807. if (invertY === void 0) { invertY = false; }
  55808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55809. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55810. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55811. };
  55812. return RawTexture;
  55813. }(BABYLON.Texture));
  55814. BABYLON.RawTexture = RawTexture;
  55815. })(BABYLON || (BABYLON = {}));
  55816. //# sourceMappingURL=babylon.rawTexture.js.map
  55817. var BABYLON;
  55818. (function (BABYLON) {
  55819. /**
  55820. * PostProcess can be used to apply a shader to a texture after it has been rendered
  55821. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  55822. */
  55823. var PostProcess = /** @class */ (function () {
  55824. /**
  55825. * Creates a new instance of @see PostProcess
  55826. * @param name The name of the PostProcess.
  55827. * @param fragmentUrl The url of the fragment shader to be used.
  55828. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  55829. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  55830. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  55831. * @param camera The camera to apply the render pass to.
  55832. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  55833. * @param engine The engine which the post process will be applied. (default: current engine)
  55834. * @param reusable If the post process can be reused on the same frame. (default: false)
  55835. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  55836. * @param textureType Type of textures used when performing the post process. (default: 0)
  55837. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  55838. * @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
  55839. * @param blockCompilation If the shader should be compiled imediatly. (default: false)
  55840. */
  55841. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55843. if (defines === void 0) { defines = null; }
  55844. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55845. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55846. if (blockCompilation === void 0) { blockCompilation = false; }
  55847. this.name = name;
  55848. /**
  55849. * Width of the texture to apply the post process on
  55850. */
  55851. this.width = -1;
  55852. /**
  55853. * Height of the texture to apply the post process on
  55854. */
  55855. this.height = -1;
  55856. /**
  55857. * If the buffer needs to be cleared before applying the post process. (default: true)
  55858. * Should be set to false if shader will overwrite all previous pixels.
  55859. */
  55860. this.autoClear = true;
  55861. /**
  55862. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  55863. */
  55864. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55865. /**
  55866. * Animations to be used for the post processing
  55867. */
  55868. this.animations = new Array();
  55869. /**
  55870. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55871. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  55872. */
  55873. this.enablePixelPerfectMode = false;
  55874. /**
  55875. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  55876. */
  55877. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55878. /**
  55879. * Force textures to be a power of two (default: false)
  55880. */
  55881. this.alwaysForcePOT = false;
  55882. /**
  55883. * Number of sample textures (default: 1)
  55884. */
  55885. this.samples = 1;
  55886. /**
  55887. * Modify the scale of the post process to be the same as the viewport (default: false)
  55888. */
  55889. this.adaptScaleToCurrentViewport = false;
  55890. this._reusable = false;
  55891. /**
  55892. * Smart array of input and output textures for the post process.
  55893. */
  55894. this._textures = new BABYLON.SmartArray(2);
  55895. /**
  55896. * The index in _textures that corresponds to the output texture.
  55897. */
  55898. this._currentRenderTextureInd = 0;
  55899. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55900. this._texelSize = BABYLON.Vector2.Zero();
  55901. // Events
  55902. /**
  55903. * An event triggered when the postprocess is activated.
  55904. * @type {BABYLON.Observable}
  55905. */
  55906. this.onActivateObservable = new BABYLON.Observable();
  55907. /**
  55908. * An event triggered when the postprocess changes its size.
  55909. * @type {BABYLON.Observable}
  55910. */
  55911. this.onSizeChangedObservable = new BABYLON.Observable();
  55912. /**
  55913. * An event triggered when the postprocess applies its effect.
  55914. * @type {BABYLON.Observable}
  55915. */
  55916. this.onApplyObservable = new BABYLON.Observable();
  55917. /**
  55918. * An event triggered before rendering the postprocess
  55919. * @type {BABYLON.Observable}
  55920. */
  55921. this.onBeforeRenderObservable = new BABYLON.Observable();
  55922. /**
  55923. * An event triggered after rendering the postprocess
  55924. * @type {BABYLON.Observable}
  55925. */
  55926. this.onAfterRenderObservable = new BABYLON.Observable();
  55927. if (camera != null) {
  55928. this._camera = camera;
  55929. this._scene = camera.getScene();
  55930. camera.attachPostProcess(this);
  55931. this._engine = this._scene.getEngine();
  55932. this._scene.postProcesses.push(this);
  55933. }
  55934. else if (engine) {
  55935. this._engine = engine;
  55936. this._engine.postProcesses.push(this);
  55937. }
  55938. this._options = options;
  55939. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55940. this._reusable = reusable || false;
  55941. this._textureType = textureType;
  55942. this._samplers = samplers || [];
  55943. this._samplers.push("textureSampler");
  55944. this._fragmentUrl = fragmentUrl;
  55945. this._vertexUrl = vertexUrl;
  55946. this._parameters = parameters || [];
  55947. this._parameters.push("scale");
  55948. this._indexParameters = indexParameters;
  55949. if (!blockCompilation) {
  55950. this.updateEffect(defines);
  55951. }
  55952. }
  55953. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55954. /**
  55955. * A function that is added to the onActivateObservable
  55956. */
  55957. set: function (callback) {
  55958. if (this._onActivateObserver) {
  55959. this.onActivateObservable.remove(this._onActivateObserver);
  55960. }
  55961. if (callback) {
  55962. this._onActivateObserver = this.onActivateObservable.add(callback);
  55963. }
  55964. },
  55965. enumerable: true,
  55966. configurable: true
  55967. });
  55968. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55969. /**
  55970. * A function that is added to the onSizeChangedObservable
  55971. */
  55972. set: function (callback) {
  55973. if (this._onSizeChangedObserver) {
  55974. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55975. }
  55976. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55977. },
  55978. enumerable: true,
  55979. configurable: true
  55980. });
  55981. Object.defineProperty(PostProcess.prototype, "onApply", {
  55982. /**
  55983. * A function that is added to the onApplyObservable
  55984. */
  55985. set: function (callback) {
  55986. if (this._onApplyObserver) {
  55987. this.onApplyObservable.remove(this._onApplyObserver);
  55988. }
  55989. this._onApplyObserver = this.onApplyObservable.add(callback);
  55990. },
  55991. enumerable: true,
  55992. configurable: true
  55993. });
  55994. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55995. /**
  55996. * A function that is added to the onBeforeRenderObservable
  55997. */
  55998. set: function (callback) {
  55999. if (this._onBeforeRenderObserver) {
  56000. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56001. }
  56002. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56003. },
  56004. enumerable: true,
  56005. configurable: true
  56006. });
  56007. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  56008. /**
  56009. * A function that is added to the onAfterRenderObservable
  56010. */
  56011. set: function (callback) {
  56012. if (this._onAfterRenderObserver) {
  56013. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56014. }
  56015. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56016. },
  56017. enumerable: true,
  56018. configurable: true
  56019. });
  56020. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  56021. /**
  56022. * The resulting output of the post process.
  56023. */
  56024. get: function () {
  56025. return this._textures.data[this._currentRenderTextureInd];
  56026. },
  56027. set: function (value) {
  56028. this._forcedOutputTexture = value;
  56029. },
  56030. enumerable: true,
  56031. configurable: true
  56032. });
  56033. /**
  56034. * Gets the camera which post process is applied to.
  56035. * @returns The camera the post process is applied to.
  56036. */
  56037. PostProcess.prototype.getCamera = function () {
  56038. return this._camera;
  56039. };
  56040. Object.defineProperty(PostProcess.prototype, "texelSize", {
  56041. /**
  56042. * Gets the texel size of the postprocess.
  56043. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  56044. */
  56045. get: function () {
  56046. if (this._shareOutputWithPostProcess) {
  56047. return this._shareOutputWithPostProcess.texelSize;
  56048. }
  56049. if (this._forcedOutputTexture) {
  56050. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  56051. }
  56052. return this._texelSize;
  56053. },
  56054. enumerable: true,
  56055. configurable: true
  56056. });
  56057. /**
  56058. * Gets the engine which this post process belongs to.
  56059. * @returns The engine the post process was enabled with.
  56060. */
  56061. PostProcess.prototype.getEngine = function () {
  56062. return this._engine;
  56063. };
  56064. /**
  56065. * The effect that is created when initializing the post process.
  56066. * @returns The created effect corrisponding the the postprocess.
  56067. */
  56068. PostProcess.prototype.getEffect = function () {
  56069. return this._effect;
  56070. };
  56071. /**
  56072. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  56073. * @param postProcess The post process to share the output with.
  56074. * @returns This post process.
  56075. */
  56076. PostProcess.prototype.shareOutputWith = function (postProcess) {
  56077. this._disposeTextures();
  56078. this._shareOutputWithPostProcess = postProcess;
  56079. return this;
  56080. };
  56081. /**
  56082. * Updates the effect with the current post process compile time values and recompiles the shader.
  56083. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  56084. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  56085. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  56086. * @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
  56087. * @param onCompiled Called when the shader has been compiled.
  56088. * @param onError Called if there is an error when compiling a shader.
  56089. */
  56090. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  56091. if (defines === void 0) { defines = null; }
  56092. if (uniforms === void 0) { uniforms = null; }
  56093. if (samplers === void 0) { samplers = null; }
  56094. 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);
  56095. };
  56096. /**
  56097. * The post process is reusable if it can be used multiple times within one frame.
  56098. * @returns If the post process is reusable
  56099. */
  56100. PostProcess.prototype.isReusable = function () {
  56101. return this._reusable;
  56102. };
  56103. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  56104. PostProcess.prototype.markTextureDirty = function () {
  56105. this.width = -1;
  56106. };
  56107. /**
  56108. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  56109. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  56110. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  56111. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  56112. */
  56113. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  56114. var _this = this;
  56115. if (sourceTexture === void 0) { sourceTexture = null; }
  56116. camera = camera || this._camera;
  56117. var scene = camera.getScene();
  56118. var engine = scene.getEngine();
  56119. var maxSize = engine.getCaps().maxTextureSize;
  56120. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  56121. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  56122. var desiredWidth = (this._options.width || requiredWidth);
  56123. var desiredHeight = this._options.height || requiredHeight;
  56124. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  56125. if (this.adaptScaleToCurrentViewport) {
  56126. var currentViewport = engine.currentViewport;
  56127. if (currentViewport) {
  56128. desiredWidth *= currentViewport.width;
  56129. desiredHeight *= currentViewport.height;
  56130. }
  56131. }
  56132. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  56133. if (!this._options.width) {
  56134. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  56135. }
  56136. if (!this._options.height) {
  56137. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  56138. }
  56139. }
  56140. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  56141. if (this._textures.length > 0) {
  56142. for (var i = 0; i < this._textures.length; i++) {
  56143. this._engine._releaseTexture(this._textures.data[i]);
  56144. }
  56145. this._textures.reset();
  56146. }
  56147. this.width = desiredWidth;
  56148. this.height = desiredHeight;
  56149. var textureSize = { width: this.width, height: this.height };
  56150. var textureOptions = {
  56151. generateMipMaps: false,
  56152. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  56153. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  56154. samplingMode: this.renderTargetSamplingMode,
  56155. type: this._textureType
  56156. };
  56157. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56158. if (this._reusable) {
  56159. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56160. }
  56161. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  56162. this.onSizeChangedObservable.notifyObservers(this);
  56163. }
  56164. this._textures.forEach(function (texture) {
  56165. if (texture.samples !== _this.samples) {
  56166. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  56167. }
  56168. });
  56169. }
  56170. var target;
  56171. if (this._shareOutputWithPostProcess) {
  56172. target = this._shareOutputWithPostProcess.outputTexture;
  56173. }
  56174. else if (this._forcedOutputTexture) {
  56175. target = this._forcedOutputTexture;
  56176. this.width = this._forcedOutputTexture.width;
  56177. this.height = this._forcedOutputTexture.height;
  56178. }
  56179. else {
  56180. target = this.outputTexture;
  56181. }
  56182. if (this.enablePixelPerfectMode) {
  56183. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  56184. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  56185. }
  56186. else {
  56187. this._scaleRatio.copyFromFloats(1, 1);
  56188. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  56189. }
  56190. this.onActivateObservable.notifyObservers(camera);
  56191. // Clear
  56192. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  56193. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  56194. }
  56195. if (this._reusable) {
  56196. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  56197. }
  56198. };
  56199. Object.defineProperty(PostProcess.prototype, "isSupported", {
  56200. /**
  56201. * If the post process is supported.
  56202. */
  56203. get: function () {
  56204. return this._effect.isSupported;
  56205. },
  56206. enumerable: true,
  56207. configurable: true
  56208. });
  56209. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  56210. /**
  56211. * The aspect ratio of the output texture.
  56212. */
  56213. get: function () {
  56214. if (this._shareOutputWithPostProcess) {
  56215. return this._shareOutputWithPostProcess.aspectRatio;
  56216. }
  56217. if (this._forcedOutputTexture) {
  56218. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  56219. }
  56220. return this.width / this.height;
  56221. },
  56222. enumerable: true,
  56223. configurable: true
  56224. });
  56225. /**
  56226. * Get a value indicating if the post-process is ready to be used
  56227. * @returns true if the post-process is ready (shader is compiled)
  56228. */
  56229. PostProcess.prototype.isReady = function () {
  56230. return this._effect && this._effect.isReady();
  56231. };
  56232. /**
  56233. * Binds all textures and uniforms to the shader, this will be run on every pass.
  56234. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  56235. */
  56236. PostProcess.prototype.apply = function () {
  56237. // Check
  56238. if (!this._effect || !this._effect.isReady())
  56239. return null;
  56240. // States
  56241. this._engine.enableEffect(this._effect);
  56242. this._engine.setState(false);
  56243. this._engine.setDepthBuffer(false);
  56244. this._engine.setDepthWrite(false);
  56245. // Alpha
  56246. this._engine.setAlphaMode(this.alphaMode);
  56247. if (this.alphaConstants) {
  56248. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  56249. }
  56250. // Texture
  56251. var source;
  56252. if (this._shareOutputWithPostProcess) {
  56253. source = this._shareOutputWithPostProcess.outputTexture;
  56254. }
  56255. else if (this._forcedOutputTexture) {
  56256. source = this._forcedOutputTexture;
  56257. }
  56258. else {
  56259. source = this.outputTexture;
  56260. }
  56261. this._effect._bindTexture("textureSampler", source);
  56262. // Parameters
  56263. this._effect.setVector2("scale", this._scaleRatio);
  56264. this.onApplyObservable.notifyObservers(this._effect);
  56265. return this._effect;
  56266. };
  56267. PostProcess.prototype._disposeTextures = function () {
  56268. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  56269. return;
  56270. }
  56271. if (this._textures.length > 0) {
  56272. for (var i = 0; i < this._textures.length; i++) {
  56273. this._engine._releaseTexture(this._textures.data[i]);
  56274. }
  56275. }
  56276. this._textures.dispose();
  56277. };
  56278. /**
  56279. * Disposes the post process.
  56280. * @param camera The camera to dispose the post process on.
  56281. */
  56282. PostProcess.prototype.dispose = function (camera) {
  56283. camera = camera || this._camera;
  56284. this._disposeTextures();
  56285. if (this._scene) {
  56286. var index_1 = this._scene.postProcesses.indexOf(this);
  56287. if (index_1 !== -1) {
  56288. this._scene.postProcesses.splice(index_1, 1);
  56289. }
  56290. }
  56291. else {
  56292. var index_2 = this._engine.postProcesses.indexOf(this);
  56293. if (index_2 !== -1) {
  56294. this._engine.postProcesses.splice(index_2, 1);
  56295. }
  56296. }
  56297. if (!camera) {
  56298. return;
  56299. }
  56300. camera.detachPostProcess(this);
  56301. var index = camera._postProcesses.indexOf(this);
  56302. if (index === 0 && camera._postProcesses.length > 0) {
  56303. this._camera._postProcesses[0].markTextureDirty();
  56304. }
  56305. this.onActivateObservable.clear();
  56306. this.onAfterRenderObservable.clear();
  56307. this.onApplyObservable.clear();
  56308. this.onBeforeRenderObservable.clear();
  56309. this.onSizeChangedObservable.clear();
  56310. };
  56311. return PostProcess;
  56312. }());
  56313. BABYLON.PostProcess = PostProcess;
  56314. })(BABYLON || (BABYLON = {}));
  56315. //# sourceMappingURL=babylon.postProcess.js.map
  56316. var BABYLON;
  56317. (function (BABYLON) {
  56318. var PassPostProcess = /** @class */ (function (_super) {
  56319. __extends(PassPostProcess, _super);
  56320. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56321. if (camera === void 0) { camera = null; }
  56322. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56323. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  56324. }
  56325. return PassPostProcess;
  56326. }(BABYLON.PostProcess));
  56327. BABYLON.PassPostProcess = PassPostProcess;
  56328. })(BABYLON || (BABYLON = {}));
  56329. //# sourceMappingURL=babylon.passPostProcess.js.map
  56330. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56331. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56332. s = arguments[i];
  56333. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56334. t[p] = s[p];
  56335. }
  56336. return t;
  56337. };
  56338. var BABYLON;
  56339. (function (BABYLON) {
  56340. /**
  56341. * Default implementation of @see IShadowGenerator.
  56342. * This is the main object responsible of generating shadows in the framework.
  56343. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  56344. */
  56345. var ShadowGenerator = /** @class */ (function () {
  56346. /**
  56347. * Creates a ShadowGenerator object.
  56348. * A ShadowGenerator is the required tool to use the shadows.
  56349. * Each light casting shadows needs to use its own ShadowGenerator.
  56350. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  56351. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  56352. * @param light The light object generating the shadows.
  56353. * @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.
  56354. */
  56355. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  56356. this._bias = 0.00005;
  56357. this._blurBoxOffset = 1;
  56358. this._blurScale = 2;
  56359. this._blurKernel = 1;
  56360. this._useKernelBlur = false;
  56361. this._filter = ShadowGenerator.FILTER_NONE;
  56362. this._darkness = 0;
  56363. this._transparencyShadow = false;
  56364. /**
  56365. * Controls the extent to which the shadows fade out at the edge of the frustum
  56366. * Used only by directionals and spots
  56367. */
  56368. this.frustumEdgeFalloff = 0;
  56369. /**
  56370. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  56371. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  56372. * It might on the other hand introduce peter panning.
  56373. */
  56374. this.forceBackFacesOnly = false;
  56375. this._lightDirection = BABYLON.Vector3.Zero();
  56376. this._viewMatrix = BABYLON.Matrix.Zero();
  56377. this._projectionMatrix = BABYLON.Matrix.Zero();
  56378. this._transformMatrix = BABYLON.Matrix.Zero();
  56379. this._currentFaceIndex = 0;
  56380. this._currentFaceIndexCache = 0;
  56381. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  56382. this._mapSize = mapSize;
  56383. this._light = light;
  56384. this._scene = light.getScene();
  56385. light._shadowGenerator = this;
  56386. // Texture type fallback from float to int if not supported.
  56387. var caps = this._scene.getEngine().getCaps();
  56388. if (!useFullFloatFirst) {
  56389. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56390. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56391. }
  56392. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56393. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56394. }
  56395. else {
  56396. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56397. }
  56398. }
  56399. else {
  56400. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56401. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56402. }
  56403. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56404. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56405. }
  56406. else {
  56407. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56408. }
  56409. }
  56410. this._initializeGenerator();
  56411. }
  56412. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  56413. /**
  56414. * Shadow generator mode None: no filtering applied.
  56415. */
  56416. get: function () {
  56417. return ShadowGenerator._FILTER_NONE;
  56418. },
  56419. enumerable: true,
  56420. configurable: true
  56421. });
  56422. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  56423. /**
  56424. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  56425. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  56426. */
  56427. get: function () {
  56428. return ShadowGenerator._FILTER_POISSONSAMPLING;
  56429. },
  56430. enumerable: true,
  56431. configurable: true
  56432. });
  56433. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  56434. /**
  56435. * Shadow generator mode ESM: Exponential Shadow Mapping.
  56436. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56437. */
  56438. get: function () {
  56439. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  56440. },
  56441. enumerable: true,
  56442. configurable: true
  56443. });
  56444. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  56445. /**
  56446. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  56447. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56448. */
  56449. get: function () {
  56450. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  56451. },
  56452. enumerable: true,
  56453. configurable: true
  56454. });
  56455. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  56456. /**
  56457. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  56458. * edge artifacts on steep falloff.
  56459. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56460. */
  56461. get: function () {
  56462. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56463. },
  56464. enumerable: true,
  56465. configurable: true
  56466. });
  56467. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  56468. /**
  56469. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  56470. * edge artifacts on steep falloff.
  56471. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56472. */
  56473. get: function () {
  56474. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56475. },
  56476. enumerable: true,
  56477. configurable: true
  56478. });
  56479. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  56480. /**
  56481. * Gets the bias: offset applied on the depth preventing acnea.
  56482. */
  56483. get: function () {
  56484. return this._bias;
  56485. },
  56486. /**
  56487. * Sets the bias: offset applied on the depth preventing acnea.
  56488. */
  56489. set: function (bias) {
  56490. this._bias = bias;
  56491. },
  56492. enumerable: true,
  56493. configurable: true
  56494. });
  56495. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  56496. /**
  56497. * Gets the blur box offset: offset applied during the blur pass.
  56498. * Only usefull if useKernelBlur = false
  56499. */
  56500. get: function () {
  56501. return this._blurBoxOffset;
  56502. },
  56503. /**
  56504. * Sets the blur box offset: offset applied during the blur pass.
  56505. * Only usefull if useKernelBlur = false
  56506. */
  56507. set: function (value) {
  56508. if (this._blurBoxOffset === value) {
  56509. return;
  56510. }
  56511. this._blurBoxOffset = value;
  56512. this._disposeBlurPostProcesses();
  56513. },
  56514. enumerable: true,
  56515. configurable: true
  56516. });
  56517. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  56518. /**
  56519. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  56520. * 2 means half of the size.
  56521. */
  56522. get: function () {
  56523. return this._blurScale;
  56524. },
  56525. /**
  56526. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  56527. * 2 means half of the size.
  56528. */
  56529. set: function (value) {
  56530. if (this._blurScale === value) {
  56531. return;
  56532. }
  56533. this._blurScale = value;
  56534. this._disposeBlurPostProcesses();
  56535. },
  56536. enumerable: true,
  56537. configurable: true
  56538. });
  56539. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  56540. /**
  56541. * Gets the blur kernel: kernel size of the blur pass.
  56542. * Only usefull if useKernelBlur = true
  56543. */
  56544. get: function () {
  56545. return this._blurKernel;
  56546. },
  56547. /**
  56548. * Sets the blur kernel: kernel size of the blur pass.
  56549. * Only usefull if useKernelBlur = true
  56550. */
  56551. set: function (value) {
  56552. if (this._blurKernel === value) {
  56553. return;
  56554. }
  56555. this._blurKernel = value;
  56556. this._disposeBlurPostProcesses();
  56557. },
  56558. enumerable: true,
  56559. configurable: true
  56560. });
  56561. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  56562. /**
  56563. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  56564. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56565. */
  56566. get: function () {
  56567. return this._useKernelBlur;
  56568. },
  56569. /**
  56570. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  56571. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56572. */
  56573. set: function (value) {
  56574. if (this._useKernelBlur === value) {
  56575. return;
  56576. }
  56577. this._useKernelBlur = value;
  56578. this._disposeBlurPostProcesses();
  56579. },
  56580. enumerable: true,
  56581. configurable: true
  56582. });
  56583. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  56584. /**
  56585. * Gets the depth scale used in ESM mode.
  56586. */
  56587. get: function () {
  56588. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  56589. },
  56590. /**
  56591. * Sets the depth scale used in ESM mode.
  56592. * This can override the scale stored on the light.
  56593. */
  56594. set: function (value) {
  56595. this._depthScale = value;
  56596. },
  56597. enumerable: true,
  56598. configurable: true
  56599. });
  56600. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  56601. /**
  56602. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  56603. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56604. */
  56605. get: function () {
  56606. return this._filter;
  56607. },
  56608. /**
  56609. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  56610. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56611. */
  56612. set: function (value) {
  56613. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  56614. if (this._light.needCube()) {
  56615. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56616. this.useExponentialShadowMap = true;
  56617. return;
  56618. }
  56619. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56620. this.useCloseExponentialShadowMap = true;
  56621. return;
  56622. }
  56623. }
  56624. if (this._filter === value) {
  56625. return;
  56626. }
  56627. this._filter = value;
  56628. this._disposeBlurPostProcesses();
  56629. this._applyFilterValues();
  56630. this._light._markMeshesAsLightDirty();
  56631. },
  56632. enumerable: true,
  56633. configurable: true
  56634. });
  56635. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  56636. /**
  56637. * Gets if the current filter is set to Poisson Sampling aka PCF.
  56638. */
  56639. get: function () {
  56640. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  56641. },
  56642. /**
  56643. * Sets the current filter to Poisson Sampling aka PCF.
  56644. */
  56645. set: function (value) {
  56646. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  56647. return;
  56648. }
  56649. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  56650. },
  56651. enumerable: true,
  56652. configurable: true
  56653. });
  56654. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  56655. /**
  56656. * Gets if the current filter is set to VSM.
  56657. * DEPRECATED. Should use useExponentialShadowMap instead.
  56658. */
  56659. get: function () {
  56660. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56661. return this.useExponentialShadowMap;
  56662. },
  56663. /**
  56664. * Sets the current filter is to VSM.
  56665. * DEPRECATED. Should use useExponentialShadowMap instead.
  56666. */
  56667. set: function (value) {
  56668. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56669. this.useExponentialShadowMap = value;
  56670. },
  56671. enumerable: true,
  56672. configurable: true
  56673. });
  56674. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  56675. /**
  56676. * Gets if the current filter is set to blurred VSM.
  56677. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56678. */
  56679. get: function () {
  56680. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56681. return this.useBlurExponentialShadowMap;
  56682. },
  56683. /**
  56684. * Sets the current filter is to blurred VSM.
  56685. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56686. */
  56687. set: function (value) {
  56688. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56689. this.useBlurExponentialShadowMap = value;
  56690. },
  56691. enumerable: true,
  56692. configurable: true
  56693. });
  56694. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  56695. /**
  56696. * Gets if the current filter is set to ESM.
  56697. */
  56698. get: function () {
  56699. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  56700. },
  56701. /**
  56702. * Sets the current filter is to ESM.
  56703. */
  56704. set: function (value) {
  56705. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  56706. return;
  56707. }
  56708. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56709. },
  56710. enumerable: true,
  56711. configurable: true
  56712. });
  56713. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  56714. /**
  56715. * Gets if the current filter is set to filtered ESM.
  56716. */
  56717. get: function () {
  56718. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  56719. },
  56720. /**
  56721. * Gets if the current filter is set to filtered ESM.
  56722. */
  56723. set: function (value) {
  56724. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56725. return;
  56726. }
  56727. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56728. },
  56729. enumerable: true,
  56730. configurable: true
  56731. });
  56732. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  56733. /**
  56734. * Gets if the current filter is set to "close ESM" (using the inverse of the
  56735. * exponential to prevent steep falloff artifacts).
  56736. */
  56737. get: function () {
  56738. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56739. },
  56740. /**
  56741. * Sets the current filter to "close ESM" (using the inverse of the
  56742. * exponential to prevent steep falloff artifacts).
  56743. */
  56744. set: function (value) {
  56745. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  56746. return;
  56747. }
  56748. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56749. },
  56750. enumerable: true,
  56751. configurable: true
  56752. });
  56753. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  56754. /**
  56755. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  56756. * exponential to prevent steep falloff artifacts).
  56757. */
  56758. get: function () {
  56759. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56760. },
  56761. /**
  56762. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  56763. * exponential to prevent steep falloff artifacts).
  56764. */
  56765. set: function (value) {
  56766. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56767. return;
  56768. }
  56769. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56770. },
  56771. enumerable: true,
  56772. configurable: true
  56773. });
  56774. /**
  56775. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  56776. * 0 means strongest and 1 would means no shadow.
  56777. * @returns the darkness.
  56778. */
  56779. ShadowGenerator.prototype.getDarkness = function () {
  56780. return this._darkness;
  56781. };
  56782. /**
  56783. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  56784. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  56785. * @returns the shadow generator allowing fluent coding.
  56786. */
  56787. ShadowGenerator.prototype.setDarkness = function (darkness) {
  56788. if (darkness >= 1.0)
  56789. this._darkness = 1.0;
  56790. else if (darkness <= 0.0)
  56791. this._darkness = 0.0;
  56792. else
  56793. this._darkness = darkness;
  56794. return this;
  56795. };
  56796. /**
  56797. * Sets the ability to have transparent shadow (boolean).
  56798. * @param transparent True if transparent else False
  56799. * @returns the shadow generator allowing fluent coding
  56800. */
  56801. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  56802. this._transparencyShadow = transparent;
  56803. return this;
  56804. };
  56805. /**
  56806. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  56807. * @returns The render target texture if present otherwise, null
  56808. */
  56809. ShadowGenerator.prototype.getShadowMap = function () {
  56810. return this._shadowMap;
  56811. };
  56812. /**
  56813. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  56814. * @returns The render target texture if the shadow map is present otherwise, null
  56815. */
  56816. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  56817. if (this._shadowMap2) {
  56818. return this._shadowMap2;
  56819. }
  56820. return this._shadowMap;
  56821. };
  56822. /**
  56823. * Helper function to add a mesh and its descendants to the list of shadow casters.
  56824. * @param mesh Mesh to add
  56825. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  56826. * @returns the Shadow Generator itself
  56827. */
  56828. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  56829. if (includeDescendants === void 0) { includeDescendants = true; }
  56830. if (!this._shadowMap) {
  56831. return this;
  56832. }
  56833. if (!this._shadowMap.renderList) {
  56834. this._shadowMap.renderList = [];
  56835. }
  56836. this._shadowMap.renderList.push(mesh);
  56837. if (includeDescendants) {
  56838. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  56839. }
  56840. return this;
  56841. var _a;
  56842. };
  56843. /**
  56844. * Helper function to remove a mesh and its descendants from the list of shadow casters
  56845. * @param mesh Mesh to remove
  56846. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  56847. * @returns the Shadow Generator itself
  56848. */
  56849. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  56850. if (includeDescendants === void 0) { includeDescendants = true; }
  56851. if (!this._shadowMap || !this._shadowMap.renderList) {
  56852. return this;
  56853. }
  56854. var index = this._shadowMap.renderList.indexOf(mesh);
  56855. if (index !== -1) {
  56856. this._shadowMap.renderList.splice(index, 1);
  56857. }
  56858. if (includeDescendants) {
  56859. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  56860. var child = _a[_i];
  56861. this.removeShadowCaster(child);
  56862. }
  56863. }
  56864. return this;
  56865. };
  56866. /**
  56867. * Returns the associated light object.
  56868. * @returns the light generating the shadow
  56869. */
  56870. ShadowGenerator.prototype.getLight = function () {
  56871. return this._light;
  56872. };
  56873. ShadowGenerator.prototype._initializeGenerator = function () {
  56874. this._light._markMeshesAsLightDirty();
  56875. this._initializeShadowMap();
  56876. };
  56877. ShadowGenerator.prototype._initializeShadowMap = function () {
  56878. var _this = this;
  56879. // Render target
  56880. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  56881. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56882. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56883. this._shadowMap.anisotropicFilteringLevel = 1;
  56884. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56885. this._shadowMap.renderParticles = false;
  56886. this._shadowMap.ignoreCameraViewport = true;
  56887. // Record Face Index before render.
  56888. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  56889. _this._currentFaceIndex = faceIndex;
  56890. });
  56891. // Custom render function.
  56892. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  56893. // Blur if required afer render.
  56894. this._shadowMap.onAfterUnbindObservable.add(function () {
  56895. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  56896. return;
  56897. }
  56898. var shadowMap = _this.getShadowMapForRendering();
  56899. if (shadowMap) {
  56900. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  56901. }
  56902. });
  56903. // Clear according to the chosen filter.
  56904. this._shadowMap.onClearObservable.add(function (engine) {
  56905. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  56906. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  56907. }
  56908. else {
  56909. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56910. }
  56911. });
  56912. };
  56913. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  56914. var _this = this;
  56915. var engine = this._scene.getEngine();
  56916. var targetSize = this._mapSize / this.blurScale;
  56917. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  56918. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  56919. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56920. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56921. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56922. }
  56923. if (this.useKernelBlur) {
  56924. 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);
  56925. this._kernelBlurXPostprocess.width = targetSize;
  56926. this._kernelBlurXPostprocess.height = targetSize;
  56927. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  56928. effect.setTexture("textureSampler", _this._shadowMap);
  56929. });
  56930. 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);
  56931. this._kernelBlurXPostprocess.autoClear = false;
  56932. this._kernelBlurYPostprocess.autoClear = false;
  56933. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56934. this._kernelBlurXPostprocess.packedFloat = true;
  56935. this._kernelBlurYPostprocess.packedFloat = true;
  56936. }
  56937. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  56938. }
  56939. else {
  56940. 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);
  56941. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  56942. effect.setFloat2("screenSize", targetSize, targetSize);
  56943. effect.setTexture("textureSampler", _this._shadowMap);
  56944. });
  56945. this._boxBlurPostprocess.autoClear = false;
  56946. this._blurPostProcesses = [this._boxBlurPostprocess];
  56947. }
  56948. };
  56949. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56950. var index;
  56951. var engine = this._scene.getEngine();
  56952. if (depthOnlySubMeshes.length) {
  56953. engine.setColorWrite(false);
  56954. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56955. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  56956. }
  56957. engine.setColorWrite(true);
  56958. }
  56959. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56960. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  56961. }
  56962. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56963. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  56964. }
  56965. if (this._transparencyShadow) {
  56966. for (index = 0; index < transparentSubMeshes.length; index++) {
  56967. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  56968. }
  56969. }
  56970. };
  56971. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  56972. var _this = this;
  56973. var mesh = subMesh.getRenderingMesh();
  56974. var scene = this._scene;
  56975. var engine = scene.getEngine();
  56976. var material = subMesh.getMaterial();
  56977. if (!material) {
  56978. return;
  56979. }
  56980. // Culling
  56981. engine.setState(material.backFaceCulling);
  56982. // Managing instances
  56983. var batch = mesh._getInstancesRenderList(subMesh._id);
  56984. if (batch.mustReturn) {
  56985. return;
  56986. }
  56987. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  56988. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  56989. engine.enableEffect(this._effect);
  56990. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  56991. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  56992. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  56993. this._effect.setVector3("lightPosition", this.getLight().position);
  56994. if (scene.activeCamera) {
  56995. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  56996. }
  56997. // Alpha test
  56998. if (material && material.needAlphaTesting()) {
  56999. var alphaTexture = material.getAlphaTestTexture();
  57000. if (alphaTexture) {
  57001. this._effect.setTexture("diffuseSampler", alphaTexture);
  57002. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  57003. }
  57004. }
  57005. // Bones
  57006. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57007. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  57008. }
  57009. if (this.forceBackFacesOnly) {
  57010. engine.setState(true, 0, false, true);
  57011. }
  57012. // Draw
  57013. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57014. if (this.forceBackFacesOnly) {
  57015. engine.setState(true, 0, false, false);
  57016. }
  57017. }
  57018. else {
  57019. // Need to reset refresh rate of the shadowMap
  57020. if (this._shadowMap) {
  57021. this._shadowMap.resetRefreshCounter();
  57022. }
  57023. }
  57024. };
  57025. ShadowGenerator.prototype._applyFilterValues = function () {
  57026. if (!this._shadowMap) {
  57027. return;
  57028. }
  57029. if (this.filter === ShadowGenerator.FILTER_NONE) {
  57030. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57031. }
  57032. else {
  57033. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57034. }
  57035. };
  57036. /**
  57037. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  57038. * @param onCompiled Callback triggered at the and of the effects compilation
  57039. * @param options Sets of optional options forcing the compilation with different modes
  57040. */
  57041. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  57042. var _this = this;
  57043. var localOptions = __assign({ useInstances: false }, options);
  57044. var shadowMap = this.getShadowMap();
  57045. if (!shadowMap) {
  57046. if (onCompiled) {
  57047. onCompiled(this);
  57048. }
  57049. return;
  57050. }
  57051. var renderList = shadowMap.renderList;
  57052. if (!renderList) {
  57053. if (onCompiled) {
  57054. onCompiled(this);
  57055. }
  57056. return;
  57057. }
  57058. var subMeshes = new Array();
  57059. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  57060. var mesh = renderList_1[_i];
  57061. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  57062. }
  57063. if (subMeshes.length === 0) {
  57064. if (onCompiled) {
  57065. onCompiled(this);
  57066. }
  57067. return;
  57068. }
  57069. var currentIndex = 0;
  57070. var checkReady = function () {
  57071. if (!_this._scene || !_this._scene.getEngine()) {
  57072. return;
  57073. }
  57074. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  57075. currentIndex++;
  57076. if (currentIndex >= subMeshes.length) {
  57077. if (onCompiled) {
  57078. onCompiled(_this);
  57079. }
  57080. return;
  57081. }
  57082. }
  57083. setTimeout(checkReady, 16);
  57084. };
  57085. checkReady();
  57086. };
  57087. /**
  57088. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  57089. * @param subMesh The submesh we want to render in the shadow map
  57090. * @param useInstances Defines wether will draw in the map using instances
  57091. * @returns true if ready otherwise, false
  57092. */
  57093. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  57094. var defines = [];
  57095. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57096. defines.push("#define FLOAT");
  57097. }
  57098. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  57099. defines.push("#define ESM");
  57100. }
  57101. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57102. var mesh = subMesh.getMesh();
  57103. var material = subMesh.getMaterial();
  57104. // Alpha test
  57105. if (material && material.needAlphaTesting()) {
  57106. var alphaTexture = material.getAlphaTestTexture();
  57107. if (alphaTexture) {
  57108. defines.push("#define ALPHATEST");
  57109. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57110. attribs.push(BABYLON.VertexBuffer.UVKind);
  57111. defines.push("#define UV1");
  57112. }
  57113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57114. if (alphaTexture.coordinatesIndex === 1) {
  57115. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57116. defines.push("#define UV2");
  57117. }
  57118. }
  57119. }
  57120. }
  57121. // Bones
  57122. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57125. if (mesh.numBoneInfluencers > 4) {
  57126. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57127. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57128. }
  57129. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57130. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57131. }
  57132. else {
  57133. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57134. }
  57135. // Instances
  57136. if (useInstances) {
  57137. defines.push("#define INSTANCES");
  57138. attribs.push("world0");
  57139. attribs.push("world1");
  57140. attribs.push("world2");
  57141. attribs.push("world3");
  57142. }
  57143. // Get correct effect
  57144. var join = defines.join("\n");
  57145. if (this._cachedDefines !== join) {
  57146. this._cachedDefines = join;
  57147. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  57148. }
  57149. if (!this._effect.isReady()) {
  57150. return false;
  57151. }
  57152. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57153. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  57154. this._initializeBlurRTTAndPostProcesses();
  57155. }
  57156. }
  57157. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  57158. return false;
  57159. }
  57160. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  57161. return false;
  57162. }
  57163. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  57164. return false;
  57165. }
  57166. return true;
  57167. };
  57168. /**
  57169. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  57170. * @param defines Defines of the material we want to update
  57171. * @param lightIndex Index of the light in the enabled light list of the material
  57172. */
  57173. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  57174. var scene = this._scene;
  57175. var light = this._light;
  57176. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57177. return;
  57178. }
  57179. defines["SHADOW" + lightIndex] = true;
  57180. if (this.usePoissonSampling) {
  57181. defines["SHADOWPCF" + lightIndex] = true;
  57182. }
  57183. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  57184. defines["SHADOWESM" + lightIndex] = true;
  57185. }
  57186. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57187. defines["SHADOWCLOSEESM" + lightIndex] = true;
  57188. }
  57189. if (light.needCube()) {
  57190. defines["SHADOWCUBE" + lightIndex] = true;
  57191. }
  57192. };
  57193. /**
  57194. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  57195. * defined in the generator but impacting the effect).
  57196. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  57197. * @param effect The effect we are binfing the information for
  57198. */
  57199. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  57200. var light = this._light;
  57201. var scene = this._scene;
  57202. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57203. return;
  57204. }
  57205. var camera = scene.activeCamera;
  57206. if (!camera) {
  57207. return;
  57208. }
  57209. var shadowMap = this.getShadowMap();
  57210. if (!shadowMap) {
  57211. return;
  57212. }
  57213. if (!light.needCube()) {
  57214. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  57215. }
  57216. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  57217. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  57218. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  57219. };
  57220. /**
  57221. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  57222. * (eq to shadow prjection matrix * light transform matrix)
  57223. * @returns The transform matrix used to create the shadow map
  57224. */
  57225. ShadowGenerator.prototype.getTransformMatrix = function () {
  57226. var scene = this._scene;
  57227. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  57228. return this._transformMatrix;
  57229. }
  57230. this._currentRenderID = scene.getRenderId();
  57231. this._currentFaceIndexCache = this._currentFaceIndex;
  57232. var lightPosition = this._light.position;
  57233. if (this._light.computeTransformedInformation()) {
  57234. lightPosition = this._light.transformedPosition;
  57235. }
  57236. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  57237. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  57238. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  57239. }
  57240. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  57241. this._cachedPosition = lightPosition.clone();
  57242. this._cachedDirection = this._lightDirection.clone();
  57243. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  57244. var shadowMap = this.getShadowMap();
  57245. if (shadowMap) {
  57246. var renderList = shadowMap.renderList;
  57247. if (renderList) {
  57248. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  57249. }
  57250. }
  57251. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  57252. }
  57253. return this._transformMatrix;
  57254. };
  57255. /**
  57256. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  57257. * Cube and 2D textures for instance.
  57258. */
  57259. ShadowGenerator.prototype.recreateShadowMap = function () {
  57260. var shadowMap = this._shadowMap;
  57261. if (!shadowMap) {
  57262. return;
  57263. }
  57264. // Track render list.
  57265. var renderList = shadowMap.renderList;
  57266. // Clean up existing data.
  57267. this._disposeRTTandPostProcesses();
  57268. // Reinitializes.
  57269. this._initializeGenerator();
  57270. // Reaffect the filter to ensure a correct fallback if necessary.
  57271. this.filter = this.filter;
  57272. // Reaffect the filter.
  57273. this._applyFilterValues();
  57274. // Reaffect Render List.
  57275. this._shadowMap.renderList = renderList;
  57276. };
  57277. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  57278. if (this._shadowMap2) {
  57279. this._shadowMap2.dispose();
  57280. this._shadowMap2 = null;
  57281. }
  57282. if (this._boxBlurPostprocess) {
  57283. this._boxBlurPostprocess.dispose();
  57284. this._boxBlurPostprocess = null;
  57285. }
  57286. if (this._kernelBlurXPostprocess) {
  57287. this._kernelBlurXPostprocess.dispose();
  57288. this._kernelBlurXPostprocess = null;
  57289. }
  57290. if (this._kernelBlurYPostprocess) {
  57291. this._kernelBlurYPostprocess.dispose();
  57292. this._kernelBlurYPostprocess = null;
  57293. }
  57294. this._blurPostProcesses = [];
  57295. };
  57296. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  57297. if (this._shadowMap) {
  57298. this._shadowMap.dispose();
  57299. this._shadowMap = null;
  57300. }
  57301. this._disposeBlurPostProcesses();
  57302. };
  57303. /**
  57304. * Disposes the ShadowGenerator.
  57305. * Returns nothing.
  57306. */
  57307. ShadowGenerator.prototype.dispose = function () {
  57308. this._disposeRTTandPostProcesses();
  57309. if (this._light) {
  57310. this._light._shadowGenerator = null;
  57311. this._light._markMeshesAsLightDirty();
  57312. }
  57313. };
  57314. /**
  57315. * Serializes the shadow generator setup to a json object.
  57316. * @returns The serialized JSON object
  57317. */
  57318. ShadowGenerator.prototype.serialize = function () {
  57319. var serializationObject = {};
  57320. var shadowMap = this.getShadowMap();
  57321. if (!shadowMap) {
  57322. return serializationObject;
  57323. }
  57324. serializationObject.lightId = this._light.id;
  57325. serializationObject.mapSize = shadowMap.getRenderSize();
  57326. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  57327. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  57328. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57329. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57330. serializationObject.usePoissonSampling = this.usePoissonSampling;
  57331. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  57332. serializationObject.depthScale = this.depthScale;
  57333. serializationObject.darkness = this.getDarkness();
  57334. serializationObject.blurBoxOffset = this.blurBoxOffset;
  57335. serializationObject.blurKernel = this.blurKernel;
  57336. serializationObject.blurScale = this.blurScale;
  57337. serializationObject.useKernelBlur = this.useKernelBlur;
  57338. serializationObject.transparencyShadow = this._transparencyShadow;
  57339. serializationObject.renderList = [];
  57340. if (shadowMap.renderList) {
  57341. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  57342. var mesh = shadowMap.renderList[meshIndex];
  57343. serializationObject.renderList.push(mesh.id);
  57344. }
  57345. }
  57346. return serializationObject;
  57347. };
  57348. /**
  57349. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  57350. * @param parsedShadowGenerator The JSON object to parse
  57351. * @param scene The scene to create the shadow map for
  57352. * @returns The parsed shadow generator
  57353. */
  57354. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  57355. //casting to point light, as light is missing the position attr and typescript complains.
  57356. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  57357. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  57358. var shadowMap = shadowGenerator.getShadowMap();
  57359. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  57360. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  57361. meshes.forEach(function (mesh) {
  57362. if (!shadowMap) {
  57363. return;
  57364. }
  57365. if (!shadowMap.renderList) {
  57366. shadowMap.renderList = [];
  57367. }
  57368. shadowMap.renderList.push(mesh);
  57369. });
  57370. }
  57371. if (parsedShadowGenerator.usePoissonSampling) {
  57372. shadowGenerator.usePoissonSampling = true;
  57373. }
  57374. else if (parsedShadowGenerator.useExponentialShadowMap) {
  57375. shadowGenerator.useExponentialShadowMap = true;
  57376. }
  57377. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  57378. shadowGenerator.useBlurExponentialShadowMap = true;
  57379. }
  57380. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  57381. shadowGenerator.useCloseExponentialShadowMap = true;
  57382. }
  57383. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  57384. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  57385. }
  57386. else if (parsedShadowGenerator.useVarianceShadowMap) {
  57387. shadowGenerator.useExponentialShadowMap = true;
  57388. }
  57389. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  57390. shadowGenerator.useBlurExponentialShadowMap = true;
  57391. }
  57392. if (parsedShadowGenerator.depthScale) {
  57393. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  57394. }
  57395. if (parsedShadowGenerator.blurScale) {
  57396. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  57397. }
  57398. if (parsedShadowGenerator.blurBoxOffset) {
  57399. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  57400. }
  57401. if (parsedShadowGenerator.useKernelBlur) {
  57402. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  57403. }
  57404. if (parsedShadowGenerator.blurKernel) {
  57405. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  57406. }
  57407. if (parsedShadowGenerator.bias !== undefined) {
  57408. shadowGenerator.bias = parsedShadowGenerator.bias;
  57409. }
  57410. if (parsedShadowGenerator.darkness) {
  57411. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  57412. }
  57413. if (parsedShadowGenerator.transparencyShadow) {
  57414. shadowGenerator.setTransparencyShadow(true);
  57415. }
  57416. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  57417. return shadowGenerator;
  57418. };
  57419. ShadowGenerator._FILTER_NONE = 0;
  57420. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  57421. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  57422. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  57423. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  57424. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  57425. return ShadowGenerator;
  57426. }());
  57427. BABYLON.ShadowGenerator = ShadowGenerator;
  57428. })(BABYLON || (BABYLON = {}));
  57429. //# sourceMappingURL=babylon.shadowGenerator.js.map
  57430. var BABYLON;
  57431. (function (BABYLON) {
  57432. var DefaultLoadingScreen = /** @class */ (function () {
  57433. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  57434. if (_loadingText === void 0) { _loadingText = ""; }
  57435. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  57436. var _this = this;
  57437. this._renderingCanvas = _renderingCanvas;
  57438. this._loadingText = _loadingText;
  57439. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  57440. // Resize
  57441. this._resizeLoadingUI = function () {
  57442. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  57443. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  57444. if (!_this._loadingDiv) {
  57445. return;
  57446. }
  57447. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  57448. _this._loadingDiv.style.left = canvasRect.left + "px";
  57449. _this._loadingDiv.style.top = canvasRect.top + "px";
  57450. _this._loadingDiv.style.width = canvasRect.width + "px";
  57451. _this._loadingDiv.style.height = canvasRect.height + "px";
  57452. };
  57453. }
  57454. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  57455. if (this._loadingDiv) {
  57456. // Do not add a loading screen if there is already one
  57457. return;
  57458. }
  57459. this._loadingDiv = document.createElement("div");
  57460. this._loadingDiv.id = "babylonjsLoadingDiv";
  57461. this._loadingDiv.style.opacity = "0";
  57462. this._loadingDiv.style.transition = "opacity 1.5s ease";
  57463. this._loadingDiv.style.pointerEvents = "none";
  57464. // Loading text
  57465. this._loadingTextDiv = document.createElement("div");
  57466. this._loadingTextDiv.style.position = "absolute";
  57467. this._loadingTextDiv.style.left = "0";
  57468. this._loadingTextDiv.style.top = "50%";
  57469. this._loadingTextDiv.style.marginTop = "80px";
  57470. this._loadingTextDiv.style.width = "100%";
  57471. this._loadingTextDiv.style.height = "20px";
  57472. this._loadingTextDiv.style.fontFamily = "Arial";
  57473. this._loadingTextDiv.style.fontSize = "14px";
  57474. this._loadingTextDiv.style.color = "white";
  57475. this._loadingTextDiv.style.textAlign = "center";
  57476. this._loadingTextDiv.innerHTML = "Loading";
  57477. this._loadingDiv.appendChild(this._loadingTextDiv);
  57478. //set the predefined text
  57479. this._loadingTextDiv.innerHTML = this._loadingText;
  57480. // Generating keyframes
  57481. var style = document.createElement('style');
  57482. style.type = 'text/css';
  57483. 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 }";
  57484. style.innerHTML = keyFrames;
  57485. document.getElementsByTagName('head')[0].appendChild(style);
  57486. // Loading img
  57487. var imgBack = new Image();
  57488. 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";
  57489. imgBack.style.position = "absolute";
  57490. imgBack.style.left = "50%";
  57491. imgBack.style.top = "50%";
  57492. imgBack.style.marginLeft = "-60px";
  57493. imgBack.style.marginTop = "-60px";
  57494. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  57495. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  57496. imgBack.style.transformOrigin = "50% 50%";
  57497. imgBack.style.webkitTransformOrigin = "50% 50%";
  57498. this._loadingDiv.appendChild(imgBack);
  57499. this._resizeLoadingUI();
  57500. window.addEventListener("resize", this._resizeLoadingUI);
  57501. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57502. document.body.appendChild(this._loadingDiv);
  57503. this._loadingDiv.style.opacity = "1";
  57504. };
  57505. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  57506. var _this = this;
  57507. if (!this._loadingDiv) {
  57508. return;
  57509. }
  57510. var onTransitionEnd = function () {
  57511. if (!_this._loadingDiv) {
  57512. return;
  57513. }
  57514. document.body.removeChild(_this._loadingDiv);
  57515. window.removeEventListener("resize", _this._resizeLoadingUI);
  57516. _this._loadingDiv = null;
  57517. };
  57518. this._loadingDiv.style.opacity = "0";
  57519. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  57520. };
  57521. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  57522. set: function (text) {
  57523. this._loadingText = text;
  57524. if (this._loadingTextDiv) {
  57525. this._loadingTextDiv.innerHTML = this._loadingText;
  57526. }
  57527. },
  57528. enumerable: true,
  57529. configurable: true
  57530. });
  57531. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  57532. get: function () {
  57533. return this._loadingDivBackgroundColor;
  57534. },
  57535. set: function (color) {
  57536. this._loadingDivBackgroundColor = color;
  57537. if (!this._loadingDiv) {
  57538. return;
  57539. }
  57540. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57541. },
  57542. enumerable: true,
  57543. configurable: true
  57544. });
  57545. return DefaultLoadingScreen;
  57546. }());
  57547. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  57548. })(BABYLON || (BABYLON = {}));
  57549. //# sourceMappingURL=babylon.loadingScreen.js.map
  57550. var BABYLON;
  57551. (function (BABYLON) {
  57552. var SceneLoaderProgressEvent = /** @class */ (function () {
  57553. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  57554. this.lengthComputable = lengthComputable;
  57555. this.loaded = loaded;
  57556. this.total = total;
  57557. }
  57558. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  57559. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  57560. };
  57561. return SceneLoaderProgressEvent;
  57562. }());
  57563. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  57564. var SceneLoader = /** @class */ (function () {
  57565. function SceneLoader() {
  57566. }
  57567. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  57568. get: function () {
  57569. return 0;
  57570. },
  57571. enumerable: true,
  57572. configurable: true
  57573. });
  57574. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  57575. get: function () {
  57576. return 1;
  57577. },
  57578. enumerable: true,
  57579. configurable: true
  57580. });
  57581. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  57582. get: function () {
  57583. return 2;
  57584. },
  57585. enumerable: true,
  57586. configurable: true
  57587. });
  57588. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  57589. get: function () {
  57590. return 3;
  57591. },
  57592. enumerable: true,
  57593. configurable: true
  57594. });
  57595. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  57596. get: function () {
  57597. return SceneLoader._ForceFullSceneLoadingForIncremental;
  57598. },
  57599. set: function (value) {
  57600. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  57601. },
  57602. enumerable: true,
  57603. configurable: true
  57604. });
  57605. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  57606. get: function () {
  57607. return SceneLoader._ShowLoadingScreen;
  57608. },
  57609. set: function (value) {
  57610. SceneLoader._ShowLoadingScreen = value;
  57611. },
  57612. enumerable: true,
  57613. configurable: true
  57614. });
  57615. Object.defineProperty(SceneLoader, "loggingLevel", {
  57616. get: function () {
  57617. return SceneLoader._loggingLevel;
  57618. },
  57619. set: function (value) {
  57620. SceneLoader._loggingLevel = value;
  57621. },
  57622. enumerable: true,
  57623. configurable: true
  57624. });
  57625. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  57626. get: function () {
  57627. return SceneLoader._CleanBoneMatrixWeights;
  57628. },
  57629. set: function (value) {
  57630. SceneLoader._CleanBoneMatrixWeights = value;
  57631. },
  57632. enumerable: true,
  57633. configurable: true
  57634. });
  57635. SceneLoader._getDefaultPlugin = function () {
  57636. return SceneLoader._registeredPlugins[".babylon"];
  57637. };
  57638. SceneLoader._getPluginForExtension = function (extension) {
  57639. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  57640. if (registeredPlugin) {
  57641. return registeredPlugin;
  57642. }
  57643. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  57644. return SceneLoader._getDefaultPlugin();
  57645. };
  57646. SceneLoader._getPluginForDirectLoad = function (data) {
  57647. for (var extension in SceneLoader._registeredPlugins) {
  57648. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  57649. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  57650. return SceneLoader._registeredPlugins[extension];
  57651. }
  57652. }
  57653. return SceneLoader._getDefaultPlugin();
  57654. };
  57655. SceneLoader._getPluginForFilename = function (sceneFilename) {
  57656. if (sceneFilename.name) {
  57657. sceneFilename = sceneFilename.name;
  57658. }
  57659. var queryStringPosition = sceneFilename.indexOf("?");
  57660. if (queryStringPosition !== -1) {
  57661. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  57662. }
  57663. var dotPosition = sceneFilename.lastIndexOf(".");
  57664. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  57665. return SceneLoader._getPluginForExtension(extension);
  57666. };
  57667. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  57668. SceneLoader._getDirectLoad = function (sceneFilename) {
  57669. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  57670. return sceneFilename.substr(5);
  57671. }
  57672. return null;
  57673. };
  57674. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  57675. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  57676. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  57677. var plugin;
  57678. if (registeredPlugin.plugin.createPlugin) {
  57679. plugin = registeredPlugin.plugin.createPlugin();
  57680. }
  57681. else {
  57682. plugin = registeredPlugin.plugin;
  57683. }
  57684. var useArrayBuffer = registeredPlugin.isBinary;
  57685. var database;
  57686. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  57687. var dataCallback = function (data, responseURL) {
  57688. if (scene.isDisposed) {
  57689. onError("Scene has been disposed");
  57690. return;
  57691. }
  57692. scene.database = database;
  57693. onSuccess(plugin, data, responseURL);
  57694. };
  57695. var request = null;
  57696. var pluginDisposed = false;
  57697. var onDisposeObservable = plugin.onDisposeObservable;
  57698. if (onDisposeObservable) {
  57699. onDisposeObservable.add(function () {
  57700. pluginDisposed = true;
  57701. if (request) {
  57702. request.abort();
  57703. request = null;
  57704. }
  57705. onDispose();
  57706. });
  57707. }
  57708. var manifestChecked = function () {
  57709. if (pluginDisposed) {
  57710. return;
  57711. }
  57712. var url = rootUrl + sceneFilename;
  57713. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  57714. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  57715. } : undefined, database, useArrayBuffer, function (request, exception) {
  57716. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  57717. });
  57718. };
  57719. if (directLoad) {
  57720. dataCallback(directLoad);
  57721. return plugin;
  57722. }
  57723. if (rootUrl.indexOf("file:") === -1) {
  57724. if (scene.getEngine().enableOfflineSupport) {
  57725. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  57726. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  57727. }
  57728. else {
  57729. manifestChecked();
  57730. }
  57731. }
  57732. else {
  57733. var fileOrString = sceneFilename;
  57734. if (fileOrString.name) {
  57735. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  57736. }
  57737. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  57738. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  57739. }
  57740. else {
  57741. onError("Unable to find file named " + sceneFilename);
  57742. }
  57743. }
  57744. return plugin;
  57745. };
  57746. // Public functions
  57747. SceneLoader.GetPluginForExtension = function (extension) {
  57748. return SceneLoader._getPluginForExtension(extension).plugin;
  57749. };
  57750. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  57751. return !!SceneLoader._registeredPlugins[extension];
  57752. };
  57753. SceneLoader.RegisterPlugin = function (plugin) {
  57754. if (typeof plugin.extensions === "string") {
  57755. var extension = plugin.extensions;
  57756. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57757. plugin: plugin,
  57758. isBinary: false
  57759. };
  57760. }
  57761. else {
  57762. var extensions = plugin.extensions;
  57763. Object.keys(extensions).forEach(function (extension) {
  57764. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57765. plugin: plugin,
  57766. isBinary: extensions[extension].isBinary
  57767. };
  57768. });
  57769. }
  57770. };
  57771. /**
  57772. * Import meshes into a scene
  57773. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  57774. * @param rootUrl a string that defines the root url for scene and resources
  57775. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57776. * @param scene the instance of BABYLON.Scene to append to
  57777. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  57778. * @param onProgress a callback with a progress event for each file being loaded
  57779. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57780. */
  57781. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57782. if (onSuccess === void 0) { onSuccess = null; }
  57783. if (onProgress === void 0) { onProgress = null; }
  57784. if (onError === void 0) { onError = null; }
  57785. if (pluginExtension === void 0) { pluginExtension = null; }
  57786. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57787. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57788. return null;
  57789. }
  57790. var loadingToken = {};
  57791. scene._addPendingData(loadingToken);
  57792. var disposeHandler = function () {
  57793. scene._removePendingData(loadingToken);
  57794. };
  57795. var errorHandler = function (message, exception) {
  57796. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  57797. if (onError) {
  57798. onError(scene, errorMessage, exception);
  57799. }
  57800. else {
  57801. BABYLON.Tools.Error(errorMessage);
  57802. // should the exception be thrown?
  57803. }
  57804. disposeHandler();
  57805. };
  57806. var progressHandler = onProgress ? function (event) {
  57807. try {
  57808. onProgress(event);
  57809. }
  57810. catch (e) {
  57811. errorHandler("Error in onProgress callback", e);
  57812. }
  57813. } : undefined;
  57814. var successHandler = function (meshes, particleSystems, skeletons) {
  57815. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  57816. if (onSuccess) {
  57817. try {
  57818. onSuccess(meshes, particleSystems, skeletons);
  57819. }
  57820. catch (e) {
  57821. errorHandler("Error in onSuccess callback", e);
  57822. }
  57823. }
  57824. scene._removePendingData(loadingToken);
  57825. };
  57826. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57827. if (plugin.rewriteRootURL) {
  57828. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  57829. }
  57830. if (sceneFilename === "") {
  57831. if (sceneFilename === "") {
  57832. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  57833. }
  57834. }
  57835. if (plugin.importMesh) {
  57836. var syncedPlugin = plugin;
  57837. var meshes = new Array();
  57838. var particleSystems = new Array();
  57839. var skeletons = new Array();
  57840. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  57841. return;
  57842. }
  57843. scene.loadingPluginName = plugin.name;
  57844. successHandler(meshes, particleSystems, skeletons);
  57845. }
  57846. else {
  57847. var asyncedPlugin = plugin;
  57848. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  57849. scene.loadingPluginName = plugin.name;
  57850. successHandler(meshes, particleSystems, skeletons);
  57851. }, progressHandler, errorHandler);
  57852. }
  57853. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57854. };
  57855. /**
  57856. * Load a scene
  57857. * @param rootUrl a string that defines the root url for scene and resources
  57858. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57859. * @param engine is the instance of BABYLON.Engine to use to create the scene
  57860. * @param onSuccess a callback with the scene when import succeeds
  57861. * @param onProgress a callback with a progress event for each file being loaded
  57862. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57863. */
  57864. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  57865. if (onSuccess === void 0) { onSuccess = null; }
  57866. if (onProgress === void 0) { onProgress = null; }
  57867. if (onError === void 0) { onError = null; }
  57868. if (pluginExtension === void 0) { pluginExtension = null; }
  57869. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  57870. };
  57871. /**
  57872. * Append a scene
  57873. * @param rootUrl a string that defines the root url for scene and resources
  57874. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57875. * @param scene is the instance of BABYLON.Scene to append to
  57876. * @param onSuccess a callback with the scene when import succeeds
  57877. * @param onProgress a callback with a progress event for each file being loaded
  57878. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57879. */
  57880. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57881. if (onSuccess === void 0) { onSuccess = null; }
  57882. if (onProgress === void 0) { onProgress = null; }
  57883. if (onError === void 0) { onError = null; }
  57884. if (pluginExtension === void 0) { pluginExtension = null; }
  57885. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57886. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57887. return null;
  57888. }
  57889. if (SceneLoader.ShowLoadingScreen) {
  57890. scene.getEngine().displayLoadingUI();
  57891. }
  57892. var loadingToken = {};
  57893. scene._addPendingData(loadingToken);
  57894. var disposeHandler = function () {
  57895. scene._removePendingData(loadingToken);
  57896. scene.getEngine().hideLoadingUI();
  57897. };
  57898. var errorHandler = function (message, exception) {
  57899. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57900. if (onError) {
  57901. onError(scene, errorMessage, exception);
  57902. }
  57903. else {
  57904. BABYLON.Tools.Error(errorMessage);
  57905. // should the exception be thrown?
  57906. }
  57907. disposeHandler();
  57908. };
  57909. var progressHandler = onProgress ? function (event) {
  57910. try {
  57911. onProgress(event);
  57912. }
  57913. catch (e) {
  57914. errorHandler("Error in onProgress callback", e);
  57915. }
  57916. } : undefined;
  57917. var successHandler = function () {
  57918. if (onSuccess) {
  57919. try {
  57920. onSuccess(scene);
  57921. }
  57922. catch (e) {
  57923. errorHandler("Error in onSuccess callback", e);
  57924. }
  57925. }
  57926. scene._removePendingData(loadingToken);
  57927. };
  57928. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57929. if (sceneFilename === "") {
  57930. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  57931. }
  57932. if (plugin.load) {
  57933. var syncedPlugin = plugin;
  57934. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  57935. return;
  57936. }
  57937. scene.loadingPluginName = plugin.name;
  57938. successHandler();
  57939. }
  57940. else {
  57941. var asyncedPlugin = plugin;
  57942. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  57943. scene.loadingPluginName = plugin.name;
  57944. successHandler();
  57945. }, progressHandler, errorHandler);
  57946. }
  57947. if (SceneLoader.ShowLoadingScreen) {
  57948. scene.executeWhenReady(function () {
  57949. scene.getEngine().hideLoadingUI();
  57950. });
  57951. }
  57952. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57953. };
  57954. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57955. if (onSuccess === void 0) { onSuccess = null; }
  57956. if (onProgress === void 0) { onProgress = null; }
  57957. if (onError === void 0) { onError = null; }
  57958. if (pluginExtension === void 0) { pluginExtension = null; }
  57959. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57960. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57961. return null;
  57962. }
  57963. var loadingToken = {};
  57964. scene._addPendingData(loadingToken);
  57965. var disposeHandler = function () {
  57966. scene._removePendingData(loadingToken);
  57967. };
  57968. var errorHandler = function (message, exception) {
  57969. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57970. if (onError) {
  57971. onError(scene, errorMessage, exception);
  57972. }
  57973. else {
  57974. BABYLON.Tools.Error(errorMessage);
  57975. // should the exception be thrown?
  57976. }
  57977. disposeHandler();
  57978. };
  57979. var progressHandler = onProgress ? function (event) {
  57980. try {
  57981. onProgress(event);
  57982. }
  57983. catch (e) {
  57984. errorHandler("Error in onProgress callback", e);
  57985. }
  57986. } : undefined;
  57987. var successHandler = function (assets) {
  57988. if (onSuccess) {
  57989. try {
  57990. onSuccess(assets);
  57991. }
  57992. catch (e) {
  57993. errorHandler("Error in onSuccess callback", e);
  57994. }
  57995. }
  57996. scene._removePendingData(loadingToken);
  57997. };
  57998. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57999. if (plugin.loadAssets) {
  58000. var syncedPlugin = plugin;
  58001. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  58002. if (!assetContainer) {
  58003. return;
  58004. }
  58005. scene.loadingPluginName = plugin.name;
  58006. successHandler(assetContainer);
  58007. }
  58008. else if (plugin.loadAssetsAsync) {
  58009. var asyncedPlugin = plugin;
  58010. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  58011. if (assetContainer) {
  58012. scene.loadingPluginName = plugin.name;
  58013. successHandler(assetContainer);
  58014. }
  58015. }, progressHandler, errorHandler);
  58016. }
  58017. else {
  58018. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  58019. }
  58020. if (SceneLoader.ShowLoadingScreen) {
  58021. scene.executeWhenReady(function () {
  58022. scene.getEngine().hideLoadingUI();
  58023. });
  58024. }
  58025. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  58026. };
  58027. // Flags
  58028. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  58029. SceneLoader._ShowLoadingScreen = true;
  58030. SceneLoader._CleanBoneMatrixWeights = false;
  58031. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  58032. // Members
  58033. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  58034. SceneLoader._registeredPlugins = {};
  58035. return SceneLoader;
  58036. }());
  58037. BABYLON.SceneLoader = SceneLoader;
  58038. ;
  58039. })(BABYLON || (BABYLON = {}));
  58040. //# sourceMappingURL=babylon.sceneLoader.js.map
  58041. var BABYLON;
  58042. (function (BABYLON) {
  58043. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  58044. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  58045. var parsedMaterial = parsedData.materials[index];
  58046. if (parsedMaterial.id === id) {
  58047. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  58048. }
  58049. }
  58050. return null;
  58051. };
  58052. var isDescendantOf = function (mesh, names, hierarchyIds) {
  58053. for (var i in names) {
  58054. if (mesh.name === names[i]) {
  58055. hierarchyIds.push(mesh.id);
  58056. return true;
  58057. }
  58058. }
  58059. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  58060. hierarchyIds.push(mesh.id);
  58061. return true;
  58062. }
  58063. return false;
  58064. };
  58065. var logOperation = function (operation, producer) {
  58066. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  58067. };
  58068. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  58069. if (addToScene === void 0) { addToScene = false; }
  58070. var container = new BABYLON.AssetContainer(scene);
  58071. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58072. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58073. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58074. // and avoid problems with multiple concurrent .babylon loads.
  58075. var log = "importScene has failed JSON parse";
  58076. try {
  58077. var parsedData = JSON.parse(data);
  58078. log = "";
  58079. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58080. var index;
  58081. var cache;
  58082. // Lights
  58083. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  58084. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  58085. var parsedLight = parsedData.lights[index];
  58086. var light = BABYLON.Light.Parse(parsedLight, scene);
  58087. if (light) {
  58088. container.lights.push(light);
  58089. log += (index === 0 ? "\n\tLights:" : "");
  58090. log += "\n\t\t" + light.toString(fullDetails);
  58091. }
  58092. }
  58093. }
  58094. // Animations
  58095. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  58096. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  58097. var parsedAnimation = parsedData.animations[index];
  58098. var animation = BABYLON.Animation.Parse(parsedAnimation);
  58099. scene.animations.push(animation);
  58100. container.animations.push(animation);
  58101. log += (index === 0 ? "\n\tAnimations:" : "");
  58102. log += "\n\t\t" + animation.toString(fullDetails);
  58103. }
  58104. }
  58105. // Materials
  58106. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  58107. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  58108. var parsedMaterial = parsedData.materials[index];
  58109. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  58110. container.materials.push(mat);
  58111. log += (index === 0 ? "\n\tMaterials:" : "");
  58112. log += "\n\t\t" + mat.toString(fullDetails);
  58113. }
  58114. }
  58115. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58116. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  58117. var parsedMultiMaterial = parsedData.multiMaterials[index];
  58118. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58119. container.multiMaterials.push(mmat);
  58120. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  58121. log += "\n\t\t" + mmat.toString(fullDetails);
  58122. }
  58123. }
  58124. // Morph targets
  58125. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  58126. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  58127. var managerData = _a[_i];
  58128. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  58129. }
  58130. }
  58131. // Skeletons
  58132. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58133. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  58134. var parsedSkeleton = parsedData.skeletons[index];
  58135. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58136. container.skeletons.push(skeleton);
  58137. log += (index === 0 ? "\n\tSkeletons:" : "");
  58138. log += "\n\t\t" + skeleton.toString(fullDetails);
  58139. }
  58140. }
  58141. // Geometries
  58142. var geometries = parsedData.geometries;
  58143. if (geometries !== undefined && geometries !== null) {
  58144. var addedGeometry = new Array();
  58145. // Boxes
  58146. var boxes = geometries.boxes;
  58147. if (boxes !== undefined && boxes !== null) {
  58148. for (index = 0, cache = boxes.length; index < cache; index++) {
  58149. var parsedBox = boxes[index];
  58150. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  58151. }
  58152. }
  58153. // Spheres
  58154. var spheres = geometries.spheres;
  58155. if (spheres !== undefined && spheres !== null) {
  58156. for (index = 0, cache = spheres.length; index < cache; index++) {
  58157. var parsedSphere = spheres[index];
  58158. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  58159. }
  58160. }
  58161. // Cylinders
  58162. var cylinders = geometries.cylinders;
  58163. if (cylinders !== undefined && cylinders !== null) {
  58164. for (index = 0, cache = cylinders.length; index < cache; index++) {
  58165. var parsedCylinder = cylinders[index];
  58166. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  58167. }
  58168. }
  58169. // Toruses
  58170. var toruses = geometries.toruses;
  58171. if (toruses !== undefined && toruses !== null) {
  58172. for (index = 0, cache = toruses.length; index < cache; index++) {
  58173. var parsedTorus = toruses[index];
  58174. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  58175. }
  58176. }
  58177. // Grounds
  58178. var grounds = geometries.grounds;
  58179. if (grounds !== undefined && grounds !== null) {
  58180. for (index = 0, cache = grounds.length; index < cache; index++) {
  58181. var parsedGround = grounds[index];
  58182. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  58183. }
  58184. }
  58185. // Planes
  58186. var planes = geometries.planes;
  58187. if (planes !== undefined && planes !== null) {
  58188. for (index = 0, cache = planes.length; index < cache; index++) {
  58189. var parsedPlane = planes[index];
  58190. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  58191. }
  58192. }
  58193. // TorusKnots
  58194. var torusKnots = geometries.torusKnots;
  58195. if (torusKnots !== undefined && torusKnots !== null) {
  58196. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  58197. var parsedTorusKnot = torusKnots[index];
  58198. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  58199. }
  58200. }
  58201. // VertexData
  58202. var vertexData = geometries.vertexData;
  58203. if (vertexData !== undefined && vertexData !== null) {
  58204. for (index = 0, cache = vertexData.length; index < cache; index++) {
  58205. var parsedVertexData = vertexData[index];
  58206. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  58207. }
  58208. }
  58209. addedGeometry.forEach(function (g) {
  58210. if (g) {
  58211. container.geometries.push(g);
  58212. }
  58213. });
  58214. }
  58215. // Transform nodes
  58216. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  58217. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  58218. var parsedTransformNode = parsedData.transformNodes[index];
  58219. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  58220. container.transformNodes.push(node);
  58221. }
  58222. }
  58223. // Meshes
  58224. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58225. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58226. var parsedMesh = parsedData.meshes[index];
  58227. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58228. container.meshes.push(mesh);
  58229. log += (index === 0 ? "\n\tMeshes:" : "");
  58230. log += "\n\t\t" + mesh.toString(fullDetails);
  58231. }
  58232. }
  58233. // Cameras
  58234. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  58235. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  58236. var parsedCamera = parsedData.cameras[index];
  58237. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  58238. container.cameras.push(camera);
  58239. log += (index === 0 ? "\n\tCameras:" : "");
  58240. log += "\n\t\t" + camera.toString(fullDetails);
  58241. }
  58242. }
  58243. // Browsing all the graph to connect the dots
  58244. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  58245. var camera = scene.cameras[index];
  58246. if (camera._waitingParentId) {
  58247. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  58248. camera._waitingParentId = null;
  58249. }
  58250. }
  58251. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58252. var light_1 = scene.lights[index];
  58253. if (light_1 && light_1._waitingParentId) {
  58254. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  58255. light_1._waitingParentId = null;
  58256. }
  58257. }
  58258. // Sounds
  58259. // TODO: add sound
  58260. var loadedSounds = [];
  58261. var loadedSound;
  58262. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  58263. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  58264. var parsedSound = parsedData.sounds[index];
  58265. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58266. if (!parsedSound.url)
  58267. parsedSound.url = parsedSound.name;
  58268. if (!loadedSounds[parsedSound.url]) {
  58269. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  58270. loadedSounds[parsedSound.url] = loadedSound;
  58271. container.sounds.push(loadedSound);
  58272. }
  58273. else {
  58274. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  58275. }
  58276. }
  58277. else {
  58278. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  58279. }
  58280. }
  58281. }
  58282. loadedSounds = [];
  58283. // Connect parents & children and parse actions
  58284. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  58285. var transformNode = scene.transformNodes[index];
  58286. if (transformNode._waitingParentId) {
  58287. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  58288. transformNode._waitingParentId = null;
  58289. }
  58290. }
  58291. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58292. var mesh = scene.meshes[index];
  58293. if (mesh._waitingParentId) {
  58294. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  58295. mesh._waitingParentId = null;
  58296. }
  58297. if (mesh._waitingActions) {
  58298. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  58299. mesh._waitingActions = null;
  58300. }
  58301. }
  58302. // freeze world matrix application
  58303. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58304. var currentMesh = scene.meshes[index];
  58305. if (currentMesh._waitingFreezeWorldMatrix) {
  58306. currentMesh.freezeWorldMatrix();
  58307. currentMesh._waitingFreezeWorldMatrix = null;
  58308. }
  58309. else {
  58310. currentMesh.computeWorldMatrix(true);
  58311. }
  58312. }
  58313. // Particles Systems
  58314. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58315. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58316. var parsedParticleSystem = parsedData.particleSystems[index];
  58317. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58318. container.particleSystems.push(ps);
  58319. }
  58320. }
  58321. // Lens flares
  58322. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  58323. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  58324. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  58325. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  58326. container.lensFlareSystems.push(lf);
  58327. }
  58328. }
  58329. // Shadows
  58330. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  58331. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  58332. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  58333. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  58334. container.shadowGenerators.push(sg);
  58335. }
  58336. }
  58337. // Lights exclusions / inclusions
  58338. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58339. var light_2 = scene.lights[index];
  58340. // Excluded check
  58341. if (light_2._excludedMeshesIds.length > 0) {
  58342. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  58343. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  58344. if (excludedMesh) {
  58345. light_2.excludedMeshes.push(excludedMesh);
  58346. }
  58347. }
  58348. light_2._excludedMeshesIds = [];
  58349. }
  58350. // Included check
  58351. if (light_2._includedOnlyMeshesIds.length > 0) {
  58352. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  58353. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  58354. if (includedOnlyMesh) {
  58355. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  58356. }
  58357. }
  58358. light_2._includedOnlyMeshesIds = [];
  58359. }
  58360. }
  58361. // Actions (scene)
  58362. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  58363. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  58364. }
  58365. if (!addToScene) {
  58366. container.removeAllFromScene();
  58367. }
  58368. return container;
  58369. }
  58370. catch (err) {
  58371. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  58372. if (onError) {
  58373. onError(msg, err);
  58374. }
  58375. else {
  58376. BABYLON.Tools.Log(msg);
  58377. throw err;
  58378. }
  58379. }
  58380. finally {
  58381. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58382. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58383. }
  58384. }
  58385. return null;
  58386. };
  58387. BABYLON.SceneLoader.RegisterPlugin({
  58388. name: "babylon.js",
  58389. extensions: ".babylon",
  58390. canDirectLoad: function (data) {
  58391. if (data.indexOf("babylon") !== -1) {
  58392. return true;
  58393. }
  58394. return false;
  58395. },
  58396. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  58397. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58398. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58399. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58400. // and avoid problems with multiple concurrent .babylon loads.
  58401. var log = "importMesh has failed JSON parse";
  58402. try {
  58403. var parsedData = JSON.parse(data);
  58404. log = "";
  58405. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58406. if (!meshesNames) {
  58407. meshesNames = null;
  58408. }
  58409. else if (!Array.isArray(meshesNames)) {
  58410. meshesNames = [meshesNames];
  58411. }
  58412. var hierarchyIds = new Array();
  58413. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58414. var loadedSkeletonsIds = [];
  58415. var loadedMaterialsIds = [];
  58416. var index;
  58417. var cache;
  58418. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58419. var parsedMesh = parsedData.meshes[index];
  58420. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  58421. if (meshesNames !== null) {
  58422. // Remove found mesh name from list.
  58423. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  58424. }
  58425. //Geometry?
  58426. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  58427. //does the file contain geometries?
  58428. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  58429. //find the correct geometry and add it to the scene
  58430. var found = false;
  58431. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  58432. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  58433. return;
  58434. }
  58435. else {
  58436. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  58437. if (parsedGeometryData.id === parsedMesh.geometryId) {
  58438. switch (geometryType) {
  58439. case "boxes":
  58440. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  58441. break;
  58442. case "spheres":
  58443. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  58444. break;
  58445. case "cylinders":
  58446. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  58447. break;
  58448. case "toruses":
  58449. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  58450. break;
  58451. case "grounds":
  58452. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  58453. break;
  58454. case "planes":
  58455. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  58456. break;
  58457. case "torusKnots":
  58458. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  58459. break;
  58460. case "vertexData":
  58461. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  58462. break;
  58463. }
  58464. found = true;
  58465. }
  58466. });
  58467. }
  58468. });
  58469. if (found === false) {
  58470. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  58471. }
  58472. }
  58473. }
  58474. // Material ?
  58475. if (parsedMesh.materialId) {
  58476. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  58477. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58478. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  58479. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  58480. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  58481. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  58482. var subMatId = parsedMultiMaterial.materials[matIndex];
  58483. loadedMaterialsIds.push(subMatId);
  58484. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  58485. log += "\n\tMaterial " + mat.toString(fullDetails);
  58486. }
  58487. loadedMaterialsIds.push(parsedMultiMaterial.id);
  58488. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58489. materialFound = true;
  58490. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  58491. break;
  58492. }
  58493. }
  58494. }
  58495. if (materialFound === false) {
  58496. loadedMaterialsIds.push(parsedMesh.materialId);
  58497. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  58498. if (!mat) {
  58499. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  58500. }
  58501. else {
  58502. log += "\n\tMaterial " + mat.toString(fullDetails);
  58503. }
  58504. }
  58505. }
  58506. // Skeleton ?
  58507. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58508. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  58509. if (skeletonAlreadyLoaded === false) {
  58510. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  58511. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  58512. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  58513. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58514. skeletons.push(skeleton);
  58515. loadedSkeletonsIds.push(parsedSkeleton.id);
  58516. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  58517. }
  58518. }
  58519. }
  58520. }
  58521. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58522. meshes.push(mesh);
  58523. log += "\n\tMesh " + mesh.toString(fullDetails);
  58524. }
  58525. }
  58526. // Connecting parents
  58527. var currentMesh;
  58528. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58529. currentMesh = scene.meshes[index];
  58530. if (currentMesh._waitingParentId) {
  58531. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  58532. currentMesh._waitingParentId = null;
  58533. }
  58534. }
  58535. // freeze and compute world matrix application
  58536. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58537. currentMesh = scene.meshes[index];
  58538. if (currentMesh._waitingFreezeWorldMatrix) {
  58539. currentMesh.freezeWorldMatrix();
  58540. currentMesh._waitingFreezeWorldMatrix = null;
  58541. }
  58542. else {
  58543. currentMesh.computeWorldMatrix(true);
  58544. }
  58545. }
  58546. }
  58547. // Particles
  58548. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58549. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58550. var parsedParticleSystem = parsedData.particleSystems[index];
  58551. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  58552. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  58553. }
  58554. }
  58555. }
  58556. return true;
  58557. }
  58558. catch (err) {
  58559. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  58560. if (onError) {
  58561. onError(msg, err);
  58562. }
  58563. else {
  58564. BABYLON.Tools.Log(msg);
  58565. throw err;
  58566. }
  58567. }
  58568. finally {
  58569. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58570. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58571. }
  58572. }
  58573. return false;
  58574. },
  58575. load: function (scene, data, rootUrl, onError) {
  58576. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58577. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58578. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58579. // and avoid problems with multiple concurrent .babylon loads.
  58580. var log = "importScene has failed JSON parse";
  58581. try {
  58582. var parsedData = JSON.parse(data);
  58583. log = "";
  58584. // Scene
  58585. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  58586. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  58587. }
  58588. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  58589. scene.autoClear = parsedData.autoClear;
  58590. }
  58591. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  58592. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  58593. }
  58594. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  58595. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  58596. }
  58597. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  58598. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  58599. }
  58600. // Fog
  58601. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  58602. scene.fogMode = parsedData.fogMode;
  58603. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  58604. scene.fogStart = parsedData.fogStart;
  58605. scene.fogEnd = parsedData.fogEnd;
  58606. scene.fogDensity = parsedData.fogDensity;
  58607. log += "\tFog mode for scene: ";
  58608. switch (scene.fogMode) {
  58609. // getters not compiling, so using hardcoded
  58610. case 1:
  58611. log += "exp\n";
  58612. break;
  58613. case 2:
  58614. log += "exp2\n";
  58615. break;
  58616. case 3:
  58617. log += "linear\n";
  58618. break;
  58619. }
  58620. }
  58621. //Physics
  58622. if (parsedData.physicsEnabled) {
  58623. var physicsPlugin;
  58624. if (parsedData.physicsEngine === "cannon") {
  58625. physicsPlugin = new BABYLON.CannonJSPlugin();
  58626. }
  58627. else if (parsedData.physicsEngine === "oimo") {
  58628. physicsPlugin = new BABYLON.OimoJSPlugin();
  58629. }
  58630. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  58631. //else - default engine, which is currently oimo
  58632. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  58633. scene.enablePhysics(physicsGravity, physicsPlugin);
  58634. }
  58635. // Metadata
  58636. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  58637. scene.metadata = parsedData.metadata;
  58638. }
  58639. //collisions, if defined. otherwise, default is true
  58640. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  58641. scene.collisionsEnabled = parsedData.collisionsEnabled;
  58642. }
  58643. scene.workerCollisions = !!parsedData.workerCollisions;
  58644. var container = loadAssets(scene, data, rootUrl, onerror, true);
  58645. if (!container) {
  58646. return false;
  58647. }
  58648. if (parsedData.autoAnimate) {
  58649. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  58650. }
  58651. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  58652. scene.setActiveCameraByID(parsedData.activeCameraID);
  58653. }
  58654. // Environment texture
  58655. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  58656. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  58657. if (parsedData.createDefaultSkybox === true) {
  58658. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  58659. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  58660. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  58661. }
  58662. }
  58663. // Finish
  58664. return true;
  58665. }
  58666. catch (err) {
  58667. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  58668. if (onError) {
  58669. onError(msg, err);
  58670. }
  58671. else {
  58672. BABYLON.Tools.Log(msg);
  58673. throw err;
  58674. }
  58675. }
  58676. finally {
  58677. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58678. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58679. }
  58680. }
  58681. return false;
  58682. },
  58683. loadAssets: function (scene, data, rootUrl, onError) {
  58684. var container = loadAssets(scene, data, rootUrl, onerror);
  58685. return container;
  58686. }
  58687. });
  58688. })(BABYLON || (BABYLON = {}));
  58689. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  58690. var BABYLON;
  58691. (function (BABYLON) {
  58692. var FilesInput = /** @class */ (function () {
  58693. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  58694. this.onProcessFileCallback = function () { return true; };
  58695. this._engine = engine;
  58696. this._currentScene = scene;
  58697. this._sceneLoadedCallback = sceneLoadedCallback;
  58698. this._progressCallback = progressCallback;
  58699. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58700. this._textureLoadingCallback = textureLoadingCallback;
  58701. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  58702. this._onReloadCallback = onReloadCallback;
  58703. this._errorCallback = errorCallback;
  58704. }
  58705. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  58706. var _this = this;
  58707. if (elementToMonitor) {
  58708. this._elementToMonitor = elementToMonitor;
  58709. this._dragEnterHandler = function (e) { _this.drag(e); };
  58710. this._dragOverHandler = function (e) { _this.drag(e); };
  58711. this._dropHandler = function (e) { _this.drop(e); };
  58712. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  58713. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  58714. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  58715. }
  58716. };
  58717. FilesInput.prototype.dispose = function () {
  58718. if (!this._elementToMonitor) {
  58719. return;
  58720. }
  58721. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  58722. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  58723. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  58724. };
  58725. FilesInput.prototype.renderFunction = function () {
  58726. if (this._additionalRenderLoopLogicCallback) {
  58727. this._additionalRenderLoopLogicCallback();
  58728. }
  58729. if (this._currentScene) {
  58730. if (this._textureLoadingCallback) {
  58731. var remaining = this._currentScene.getWaitingItemsCount();
  58732. if (remaining > 0) {
  58733. this._textureLoadingCallback(remaining);
  58734. }
  58735. }
  58736. this._currentScene.render();
  58737. }
  58738. };
  58739. FilesInput.prototype.drag = function (e) {
  58740. e.stopPropagation();
  58741. e.preventDefault();
  58742. };
  58743. FilesInput.prototype.drop = function (eventDrop) {
  58744. eventDrop.stopPropagation();
  58745. eventDrop.preventDefault();
  58746. this.loadFiles(eventDrop);
  58747. };
  58748. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  58749. var _this = this;
  58750. var reader = folder.createReader();
  58751. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  58752. reader.readEntries(function (entries) {
  58753. remaining.count += entries.length;
  58754. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  58755. var entry = entries_1[_i];
  58756. if (entry.isFile) {
  58757. entry.file(function (file) {
  58758. file.correctName = relativePath + file.name;
  58759. files.push(file);
  58760. if (--remaining.count === 0) {
  58761. callback();
  58762. }
  58763. });
  58764. }
  58765. else if (entry.isDirectory) {
  58766. _this._traverseFolder(entry, files, remaining, callback);
  58767. }
  58768. }
  58769. if (--remaining.count) {
  58770. callback();
  58771. }
  58772. });
  58773. };
  58774. FilesInput.prototype._processFiles = function (files) {
  58775. for (var i = 0; i < files.length; i++) {
  58776. var name = files[i].correctName.toLowerCase();
  58777. var extension = name.split('.').pop();
  58778. if (!this.onProcessFileCallback(files[i], name, extension)) {
  58779. continue;
  58780. }
  58781. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  58782. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  58783. this._sceneFileToLoad = files[i];
  58784. }
  58785. else {
  58786. FilesInput.FilesToLoad[name] = files[i];
  58787. }
  58788. }
  58789. };
  58790. FilesInput.prototype.loadFiles = function (event) {
  58791. var _this = this;
  58792. if (this._startingProcessingFilesCallback)
  58793. this._startingProcessingFilesCallback();
  58794. // Handling data transfer via drag'n'drop
  58795. if (event && event.dataTransfer && event.dataTransfer.files) {
  58796. this._filesToLoad = event.dataTransfer.files;
  58797. }
  58798. // Handling files from input files
  58799. if (event && event.target && event.target.files) {
  58800. this._filesToLoad = event.target.files;
  58801. }
  58802. if (this._filesToLoad && this._filesToLoad.length > 0) {
  58803. var files_1 = new Array();
  58804. var folders = [];
  58805. var items = event.dataTransfer ? event.dataTransfer.items : null;
  58806. for (var i = 0; i < this._filesToLoad.length; i++) {
  58807. var fileToLoad = this._filesToLoad[i];
  58808. var name_1 = fileToLoad.name.toLowerCase();
  58809. var entry = void 0;
  58810. fileToLoad.correctName = name_1;
  58811. if (items) {
  58812. var item = items[i];
  58813. if (item.getAsEntry) {
  58814. entry = item.getAsEntry();
  58815. }
  58816. else if (item.webkitGetAsEntry) {
  58817. entry = item.webkitGetAsEntry();
  58818. }
  58819. }
  58820. if (!entry) {
  58821. files_1.push(fileToLoad);
  58822. }
  58823. else {
  58824. if (entry.isDirectory) {
  58825. folders.push(entry);
  58826. }
  58827. else {
  58828. files_1.push(fileToLoad);
  58829. }
  58830. }
  58831. }
  58832. if (folders.length === 0) {
  58833. this._processFiles(files_1);
  58834. this._processReload();
  58835. }
  58836. else {
  58837. var remaining = { count: folders.length };
  58838. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  58839. var folder = folders_1[_i];
  58840. this._traverseFolder(folder, files_1, remaining, function () {
  58841. _this._processFiles(files_1);
  58842. if (remaining.count === 0) {
  58843. _this._processReload();
  58844. }
  58845. });
  58846. }
  58847. }
  58848. }
  58849. };
  58850. FilesInput.prototype._processReload = function () {
  58851. if (this._onReloadCallback) {
  58852. this._onReloadCallback(this._sceneFileToLoad);
  58853. }
  58854. else {
  58855. this.reload();
  58856. }
  58857. };
  58858. FilesInput.prototype.reload = function () {
  58859. var _this = this;
  58860. // If a scene file has been provided
  58861. if (this._sceneFileToLoad) {
  58862. if (this._currentScene) {
  58863. if (BABYLON.Tools.errorsCount > 0) {
  58864. BABYLON.Tools.ClearLogCache();
  58865. }
  58866. this._engine.stopRenderLoop();
  58867. this._currentScene.dispose();
  58868. }
  58869. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  58870. _this._currentScene = newScene;
  58871. if (_this._sceneLoadedCallback) {
  58872. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  58873. }
  58874. // Wait for textures and shaders to be ready
  58875. _this._currentScene.executeWhenReady(function () {
  58876. _this._engine.runRenderLoop(function () {
  58877. _this.renderFunction();
  58878. });
  58879. });
  58880. }, function (progress) {
  58881. if (_this._progressCallback) {
  58882. _this._progressCallback(progress);
  58883. }
  58884. }, function (scene, message) {
  58885. _this._currentScene = scene;
  58886. if (_this._errorCallback) {
  58887. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  58888. }
  58889. });
  58890. }
  58891. else {
  58892. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  58893. }
  58894. };
  58895. FilesInput.FilesToLoad = {};
  58896. return FilesInput;
  58897. }());
  58898. BABYLON.FilesInput = FilesInput;
  58899. })(BABYLON || (BABYLON = {}));
  58900. //# sourceMappingURL=babylon.filesInput.js.map
  58901. var BABYLON;
  58902. (function (BABYLON) {
  58903. /**
  58904. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58905. * The underlying implementation relies on an associative array to ensure the best performances.
  58906. * The value can be anything including 'null' but except 'undefined'
  58907. */
  58908. var StringDictionary = /** @class */ (function () {
  58909. function StringDictionary() {
  58910. this._count = 0;
  58911. this._data = {};
  58912. }
  58913. /**
  58914. * This will clear this dictionary and copy the content from the 'source' one.
  58915. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58916. * @param source the dictionary to take the content from and copy to this dictionary
  58917. */
  58918. StringDictionary.prototype.copyFrom = function (source) {
  58919. var _this = this;
  58920. this.clear();
  58921. source.forEach(function (t, v) { return _this.add(t, v); });
  58922. };
  58923. /**
  58924. * Get a value based from its key
  58925. * @param key the given key to get the matching value from
  58926. * @return the value if found, otherwise undefined is returned
  58927. */
  58928. StringDictionary.prototype.get = function (key) {
  58929. var val = this._data[key];
  58930. if (val !== undefined) {
  58931. return val;
  58932. }
  58933. return undefined;
  58934. };
  58935. /**
  58936. * Get a value from its key or add it if it doesn't exist.
  58937. * This method will ensure you that a given key/data will be present in the dictionary.
  58938. * @param key the given key to get the matching value from
  58939. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58940. * The factory will only be invoked if there's no data for the given key.
  58941. * @return the value corresponding to the key.
  58942. */
  58943. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58944. var val = this.get(key);
  58945. if (val !== undefined) {
  58946. return val;
  58947. }
  58948. val = factory(key);
  58949. if (val) {
  58950. this.add(key, val);
  58951. }
  58952. return val;
  58953. };
  58954. /**
  58955. * Get a value from its key if present in the dictionary otherwise add it
  58956. * @param key the key to get the value from
  58957. * @param val if there's no such key/value pair in the dictionary add it with this value
  58958. * @return the value corresponding to the key
  58959. */
  58960. StringDictionary.prototype.getOrAdd = function (key, val) {
  58961. var curVal = this.get(key);
  58962. if (curVal !== undefined) {
  58963. return curVal;
  58964. }
  58965. this.add(key, val);
  58966. return val;
  58967. };
  58968. /**
  58969. * Check if there's a given key in the dictionary
  58970. * @param key the key to check for
  58971. * @return true if the key is present, false otherwise
  58972. */
  58973. StringDictionary.prototype.contains = function (key) {
  58974. return this._data[key] !== undefined;
  58975. };
  58976. /**
  58977. * Add a new key and its corresponding value
  58978. * @param key the key to add
  58979. * @param value the value corresponding to the key
  58980. * @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
  58981. */
  58982. StringDictionary.prototype.add = function (key, value) {
  58983. if (this._data[key] !== undefined) {
  58984. return false;
  58985. }
  58986. this._data[key] = value;
  58987. ++this._count;
  58988. return true;
  58989. };
  58990. StringDictionary.prototype.set = function (key, value) {
  58991. if (this._data[key] === undefined) {
  58992. return false;
  58993. }
  58994. this._data[key] = value;
  58995. return true;
  58996. };
  58997. /**
  58998. * Get the element of the given key and remove it from the dictionary
  58999. * @param key
  59000. */
  59001. StringDictionary.prototype.getAndRemove = function (key) {
  59002. var val = this.get(key);
  59003. if (val !== undefined) {
  59004. delete this._data[key];
  59005. --this._count;
  59006. return val;
  59007. }
  59008. return null;
  59009. };
  59010. /**
  59011. * Remove a key/value from the dictionary.
  59012. * @param key the key to remove
  59013. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59014. */
  59015. StringDictionary.prototype.remove = function (key) {
  59016. if (this.contains(key)) {
  59017. delete this._data[key];
  59018. --this._count;
  59019. return true;
  59020. }
  59021. return false;
  59022. };
  59023. /**
  59024. * Clear the whole content of the dictionary
  59025. */
  59026. StringDictionary.prototype.clear = function () {
  59027. this._data = {};
  59028. this._count = 0;
  59029. };
  59030. Object.defineProperty(StringDictionary.prototype, "count", {
  59031. get: function () {
  59032. return this._count;
  59033. },
  59034. enumerable: true,
  59035. configurable: true
  59036. });
  59037. /**
  59038. * Execute a callback on each key/val of the dictionary.
  59039. * Note that you can remove any element in this dictionary in the callback implementation
  59040. * @param callback the callback to execute on a given key/value pair
  59041. */
  59042. StringDictionary.prototype.forEach = function (callback) {
  59043. for (var cur in this._data) {
  59044. var val = this._data[cur];
  59045. callback(cur, val);
  59046. }
  59047. };
  59048. /**
  59049. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59050. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59051. * Note that you can remove any element in this dictionary in the callback implementation
  59052. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59053. */
  59054. StringDictionary.prototype.first = function (callback) {
  59055. for (var cur in this._data) {
  59056. var val = this._data[cur];
  59057. var res = callback(cur, val);
  59058. if (res) {
  59059. return res;
  59060. }
  59061. }
  59062. return null;
  59063. };
  59064. return StringDictionary;
  59065. }());
  59066. BABYLON.StringDictionary = StringDictionary;
  59067. })(BABYLON || (BABYLON = {}));
  59068. //# sourceMappingURL=babylon.stringDictionary.js.map
  59069. var BABYLON;
  59070. (function (BABYLON) {
  59071. var Tags = /** @class */ (function () {
  59072. function Tags() {
  59073. }
  59074. Tags.EnableFor = function (obj) {
  59075. obj._tags = obj._tags || {};
  59076. obj.hasTags = function () {
  59077. return Tags.HasTags(obj);
  59078. };
  59079. obj.addTags = function (tagsString) {
  59080. return Tags.AddTagsTo(obj, tagsString);
  59081. };
  59082. obj.removeTags = function (tagsString) {
  59083. return Tags.RemoveTagsFrom(obj, tagsString);
  59084. };
  59085. obj.matchesTagsQuery = function (tagsQuery) {
  59086. return Tags.MatchesQuery(obj, tagsQuery);
  59087. };
  59088. };
  59089. Tags.DisableFor = function (obj) {
  59090. delete obj._tags;
  59091. delete obj.hasTags;
  59092. delete obj.addTags;
  59093. delete obj.removeTags;
  59094. delete obj.matchesTagsQuery;
  59095. };
  59096. Tags.HasTags = function (obj) {
  59097. if (!obj._tags) {
  59098. return false;
  59099. }
  59100. return !BABYLON.Tools.IsEmpty(obj._tags);
  59101. };
  59102. Tags.GetTags = function (obj, asString) {
  59103. if (asString === void 0) { asString = true; }
  59104. if (!obj._tags) {
  59105. return null;
  59106. }
  59107. if (asString) {
  59108. var tagsArray = [];
  59109. for (var tag in obj._tags) {
  59110. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  59111. tagsArray.push(tag);
  59112. }
  59113. }
  59114. return tagsArray.join(" ");
  59115. }
  59116. else {
  59117. return obj._tags;
  59118. }
  59119. };
  59120. // the tags 'true' and 'false' are reserved and cannot be used as tags
  59121. // a tag cannot start with '||', '&&', and '!'
  59122. // it cannot contain whitespaces
  59123. Tags.AddTagsTo = function (obj, tagsString) {
  59124. if (!tagsString) {
  59125. return;
  59126. }
  59127. if (typeof tagsString !== "string") {
  59128. return;
  59129. }
  59130. var tags = tagsString.split(" ");
  59131. tags.forEach(function (tag, index, array) {
  59132. Tags._AddTagTo(obj, tag);
  59133. });
  59134. };
  59135. Tags._AddTagTo = function (obj, tag) {
  59136. tag = tag.trim();
  59137. if (tag === "" || tag === "true" || tag === "false") {
  59138. return;
  59139. }
  59140. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  59141. return;
  59142. }
  59143. Tags.EnableFor(obj);
  59144. obj._tags[tag] = true;
  59145. };
  59146. Tags.RemoveTagsFrom = function (obj, tagsString) {
  59147. if (!Tags.HasTags(obj)) {
  59148. return;
  59149. }
  59150. var tags = tagsString.split(" ");
  59151. for (var t in tags) {
  59152. Tags._RemoveTagFrom(obj, tags[t]);
  59153. }
  59154. };
  59155. Tags._RemoveTagFrom = function (obj, tag) {
  59156. delete obj._tags[tag];
  59157. };
  59158. Tags.MatchesQuery = function (obj, tagsQuery) {
  59159. if (tagsQuery === undefined) {
  59160. return true;
  59161. }
  59162. if (tagsQuery === "") {
  59163. return Tags.HasTags(obj);
  59164. }
  59165. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  59166. };
  59167. return Tags;
  59168. }());
  59169. BABYLON.Tags = Tags;
  59170. })(BABYLON || (BABYLON = {}));
  59171. //# sourceMappingURL=babylon.tags.js.map
  59172. var BABYLON;
  59173. (function (BABYLON) {
  59174. var AndOrNotEvaluator = /** @class */ (function () {
  59175. function AndOrNotEvaluator() {
  59176. }
  59177. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  59178. if (!query.match(/\([^\(\)]*\)/g)) {
  59179. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  59180. }
  59181. else {
  59182. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  59183. // remove parenthesis
  59184. r = r.slice(1, r.length - 1);
  59185. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  59186. });
  59187. }
  59188. if (query === "true") {
  59189. return true;
  59190. }
  59191. if (query === "false") {
  59192. return false;
  59193. }
  59194. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  59195. };
  59196. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  59197. evaluateCallback = evaluateCallback || (function (r) {
  59198. return r === "true" ? true : false;
  59199. });
  59200. var result;
  59201. var or = parenthesisContent.split("||");
  59202. for (var i in or) {
  59203. if (or.hasOwnProperty(i)) {
  59204. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  59205. var and = ori.split("&&");
  59206. if (and.length > 1) {
  59207. for (var j = 0; j < and.length; ++j) {
  59208. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  59209. if (andj !== "true" && andj !== "false") {
  59210. if (andj[0] === "!") {
  59211. result = !evaluateCallback(andj.substring(1));
  59212. }
  59213. else {
  59214. result = evaluateCallback(andj);
  59215. }
  59216. }
  59217. else {
  59218. result = andj === "true" ? true : false;
  59219. }
  59220. if (!result) {
  59221. ori = "false";
  59222. break;
  59223. }
  59224. }
  59225. }
  59226. if (result || ori === "true") {
  59227. result = true;
  59228. break;
  59229. }
  59230. // result equals false (or undefined)
  59231. if (ori !== "true" && ori !== "false") {
  59232. if (ori[0] === "!") {
  59233. result = !evaluateCallback(ori.substring(1));
  59234. }
  59235. else {
  59236. result = evaluateCallback(ori);
  59237. }
  59238. }
  59239. else {
  59240. result = ori === "true" ? true : false;
  59241. }
  59242. }
  59243. }
  59244. // the whole parenthesis scope is replaced by 'true' or 'false'
  59245. return result ? "true" : "false";
  59246. };
  59247. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  59248. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  59249. // remove whitespaces
  59250. r = r.replace(/[\s]/g, function () { return ""; });
  59251. return r.length % 2 ? "!" : "";
  59252. });
  59253. booleanString = booleanString.trim();
  59254. if (booleanString === "!true") {
  59255. booleanString = "false";
  59256. }
  59257. else if (booleanString === "!false") {
  59258. booleanString = "true";
  59259. }
  59260. return booleanString;
  59261. };
  59262. return AndOrNotEvaluator;
  59263. }());
  59264. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  59265. })(BABYLON || (BABYLON = {}));
  59266. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  59267. var BABYLON;
  59268. (function (BABYLON) {
  59269. var Database = /** @class */ (function () {
  59270. function Database(urlToScene, callbackManifestChecked) {
  59271. // Handling various flavors of prefixed version of IndexedDB
  59272. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  59273. this.callbackManifestChecked = callbackManifestChecked;
  59274. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  59275. this.db = null;
  59276. this._enableSceneOffline = false;
  59277. this._enableTexturesOffline = false;
  59278. this.manifestVersionFound = 0;
  59279. this.mustUpdateRessources = false;
  59280. this.hasReachedQuota = false;
  59281. if (!Database.IDBStorageEnabled) {
  59282. this.callbackManifestChecked(true);
  59283. }
  59284. else {
  59285. this.checkManifestFile();
  59286. }
  59287. }
  59288. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  59289. get: function () {
  59290. return this._enableSceneOffline;
  59291. },
  59292. enumerable: true,
  59293. configurable: true
  59294. });
  59295. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  59296. get: function () {
  59297. return this._enableTexturesOffline;
  59298. },
  59299. enumerable: true,
  59300. configurable: true
  59301. });
  59302. Database.prototype.checkManifestFile = function () {
  59303. var _this = this;
  59304. var noManifestFile = function () {
  59305. _this._enableSceneOffline = false;
  59306. _this._enableTexturesOffline = false;
  59307. _this.callbackManifestChecked(false);
  59308. };
  59309. var timeStampUsed = false;
  59310. var manifestURL = this.currentSceneUrl + ".manifest";
  59311. var xhr = new XMLHttpRequest();
  59312. if (navigator.onLine) {
  59313. // Adding a timestamp to by-pass browsers' cache
  59314. timeStampUsed = true;
  59315. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  59316. }
  59317. xhr.open("GET", manifestURL, true);
  59318. xhr.addEventListener("load", function () {
  59319. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59320. try {
  59321. var manifestFile = JSON.parse(xhr.response);
  59322. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  59323. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  59324. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  59325. _this.manifestVersionFound = manifestFile.version;
  59326. }
  59327. if (_this.callbackManifestChecked) {
  59328. _this.callbackManifestChecked(true);
  59329. }
  59330. }
  59331. catch (ex) {
  59332. noManifestFile();
  59333. }
  59334. }
  59335. else {
  59336. noManifestFile();
  59337. }
  59338. }, false);
  59339. xhr.addEventListener("error", function (event) {
  59340. if (timeStampUsed) {
  59341. timeStampUsed = false;
  59342. // Let's retry without the timeStamp
  59343. // It could fail when coupled with HTML5 Offline API
  59344. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  59345. xhr.open("GET", retryManifestURL, true);
  59346. xhr.send();
  59347. }
  59348. else {
  59349. noManifestFile();
  59350. }
  59351. }, false);
  59352. try {
  59353. xhr.send();
  59354. }
  59355. catch (ex) {
  59356. BABYLON.Tools.Error("Error on XHR send request.");
  59357. this.callbackManifestChecked(false);
  59358. }
  59359. };
  59360. Database.prototype.openAsync = function (successCallback, errorCallback) {
  59361. var _this = this;
  59362. var handleError = function () {
  59363. _this.isSupported = false;
  59364. if (errorCallback)
  59365. errorCallback();
  59366. };
  59367. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  59368. // Your browser doesn't support IndexedDB
  59369. this.isSupported = false;
  59370. if (errorCallback)
  59371. errorCallback();
  59372. }
  59373. else {
  59374. // If the DB hasn't been opened or created yet
  59375. if (!this.db) {
  59376. this.hasReachedQuota = false;
  59377. this.isSupported = true;
  59378. var request = this.idbFactory.open("babylonjs", 1);
  59379. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  59380. request.onerror = function (event) {
  59381. handleError();
  59382. };
  59383. // executes when a version change transaction cannot complete due to other active transactions
  59384. request.onblocked = function (event) {
  59385. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  59386. handleError();
  59387. };
  59388. // DB has been opened successfully
  59389. request.onsuccess = function (event) {
  59390. _this.db = request.result;
  59391. successCallback();
  59392. };
  59393. // Initialization of the DB. Creating Scenes & Textures stores
  59394. request.onupgradeneeded = function (event) {
  59395. _this.db = (event.target).result;
  59396. if (_this.db) {
  59397. try {
  59398. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  59399. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  59400. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  59401. }
  59402. catch (ex) {
  59403. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  59404. handleError();
  59405. }
  59406. }
  59407. };
  59408. }
  59409. else {
  59410. if (successCallback)
  59411. successCallback();
  59412. }
  59413. }
  59414. };
  59415. Database.prototype.loadImageFromDB = function (url, image) {
  59416. var _this = this;
  59417. var completeURL = Database.ReturnFullUrlLocation(url);
  59418. var saveAndLoadImage = function () {
  59419. if (!_this.hasReachedQuota && _this.db !== null) {
  59420. // the texture is not yet in the DB, let's try to save it
  59421. _this._saveImageIntoDBAsync(completeURL, image);
  59422. }
  59423. else {
  59424. image.src = url;
  59425. }
  59426. };
  59427. if (!this.mustUpdateRessources) {
  59428. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  59429. }
  59430. else {
  59431. saveAndLoadImage();
  59432. }
  59433. };
  59434. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  59435. if (this.isSupported && this.db !== null) {
  59436. var texture;
  59437. var transaction = this.db.transaction(["textures"]);
  59438. transaction.onabort = function (event) {
  59439. image.src = url;
  59440. };
  59441. transaction.oncomplete = function (event) {
  59442. var blobTextureURL;
  59443. if (texture) {
  59444. var URL = window.URL || window.webkitURL;
  59445. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  59446. image.onerror = function () {
  59447. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  59448. image.src = url;
  59449. };
  59450. image.src = blobTextureURL;
  59451. }
  59452. else {
  59453. notInDBCallback();
  59454. }
  59455. };
  59456. var getRequest = transaction.objectStore("textures").get(url);
  59457. getRequest.onsuccess = function (event) {
  59458. texture = (event.target).result;
  59459. };
  59460. getRequest.onerror = function (event) {
  59461. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  59462. image.src = url;
  59463. };
  59464. }
  59465. else {
  59466. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59467. image.src = url;
  59468. }
  59469. };
  59470. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  59471. var _this = this;
  59472. if (this.isSupported) {
  59473. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  59474. var generateBlobUrl = function () {
  59475. var blobTextureURL;
  59476. if (blob) {
  59477. var URL = window.URL || window.webkitURL;
  59478. try {
  59479. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  59480. }
  59481. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  59482. catch (ex) {
  59483. blobTextureURL = URL.createObjectURL(blob);
  59484. }
  59485. }
  59486. if (blobTextureURL) {
  59487. image.src = blobTextureURL;
  59488. }
  59489. };
  59490. if (Database.IsUASupportingBlobStorage) {
  59491. var xhr = new XMLHttpRequest(), blob;
  59492. xhr.open("GET", url, true);
  59493. xhr.responseType = "blob";
  59494. xhr.addEventListener("load", function () {
  59495. if (xhr.status === 200 && _this.db) {
  59496. // Blob as response (XHR2)
  59497. blob = xhr.response;
  59498. var transaction = _this.db.transaction(["textures"], "readwrite");
  59499. // the transaction could abort because of a QuotaExceededError error
  59500. transaction.onabort = function (event) {
  59501. try {
  59502. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59503. var srcElement = (event.srcElement || event.target);
  59504. var error = srcElement.error;
  59505. if (error && error.name === "QuotaExceededError") {
  59506. _this.hasReachedQuota = true;
  59507. }
  59508. }
  59509. catch (ex) { }
  59510. generateBlobUrl();
  59511. };
  59512. transaction.oncomplete = function (event) {
  59513. generateBlobUrl();
  59514. };
  59515. var newTexture = { textureUrl: url, data: blob };
  59516. try {
  59517. // Put the blob into the dabase
  59518. var addRequest = transaction.objectStore("textures").put(newTexture);
  59519. addRequest.onsuccess = function (event) {
  59520. };
  59521. addRequest.onerror = function (event) {
  59522. generateBlobUrl();
  59523. };
  59524. }
  59525. catch (ex) {
  59526. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  59527. if (ex.code === 25) {
  59528. Database.IsUASupportingBlobStorage = false;
  59529. }
  59530. image.src = url;
  59531. }
  59532. }
  59533. else {
  59534. image.src = url;
  59535. }
  59536. }, false);
  59537. xhr.addEventListener("error", function (event) {
  59538. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  59539. image.src = url;
  59540. }, false);
  59541. xhr.send();
  59542. }
  59543. else {
  59544. image.src = url;
  59545. }
  59546. }
  59547. else {
  59548. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59549. image.src = url;
  59550. }
  59551. };
  59552. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  59553. var _this = this;
  59554. var updateVersion = function () {
  59555. // the version is not yet in the DB or we need to update it
  59556. _this._saveVersionIntoDBAsync(url, versionLoaded);
  59557. };
  59558. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  59559. };
  59560. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  59561. var _this = this;
  59562. if (this.isSupported && this.db) {
  59563. var version;
  59564. try {
  59565. var transaction = this.db.transaction(["versions"]);
  59566. transaction.oncomplete = function (event) {
  59567. if (version) {
  59568. // If the version in the JSON file is > than the version in DB
  59569. if (_this.manifestVersionFound > version.data) {
  59570. _this.mustUpdateRessources = true;
  59571. updateInDBCallback();
  59572. }
  59573. else {
  59574. callback(version.data);
  59575. }
  59576. }
  59577. else {
  59578. _this.mustUpdateRessources = true;
  59579. updateInDBCallback();
  59580. }
  59581. };
  59582. transaction.onabort = function (event) {
  59583. callback(-1);
  59584. };
  59585. var getRequest = transaction.objectStore("versions").get(url);
  59586. getRequest.onsuccess = function (event) {
  59587. version = (event.target).result;
  59588. };
  59589. getRequest.onerror = function (event) {
  59590. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  59591. callback(-1);
  59592. };
  59593. }
  59594. catch (ex) {
  59595. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  59596. callback(-1);
  59597. }
  59598. }
  59599. else {
  59600. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59601. callback(-1);
  59602. }
  59603. };
  59604. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  59605. var _this = this;
  59606. if (this.isSupported && !this.hasReachedQuota && this.db) {
  59607. try {
  59608. // Open a transaction to the database
  59609. var transaction = this.db.transaction(["versions"], "readwrite");
  59610. // the transaction could abort because of a QuotaExceededError error
  59611. transaction.onabort = function (event) {
  59612. try {
  59613. var error = event.srcElement['error'];
  59614. if (error && error.name === "QuotaExceededError") {
  59615. _this.hasReachedQuota = true;
  59616. }
  59617. }
  59618. catch (ex) { }
  59619. callback(-1);
  59620. };
  59621. transaction.oncomplete = function (event) {
  59622. callback(_this.manifestVersionFound);
  59623. };
  59624. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  59625. // Put the scene into the database
  59626. var addRequest = transaction.objectStore("versions").put(newVersion);
  59627. addRequest.onsuccess = function (event) {
  59628. };
  59629. addRequest.onerror = function (event) {
  59630. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  59631. };
  59632. }
  59633. catch (ex) {
  59634. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  59635. callback(-1);
  59636. }
  59637. }
  59638. else {
  59639. callback(-1);
  59640. }
  59641. };
  59642. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  59643. var _this = this;
  59644. var completeUrl = Database.ReturnFullUrlLocation(url);
  59645. var saveAndLoadFile = function () {
  59646. // the scene is not yet in the DB, let's try to save it
  59647. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  59648. };
  59649. this._checkVersionFromDB(completeUrl, function (version) {
  59650. if (version !== -1) {
  59651. if (!_this.mustUpdateRessources) {
  59652. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  59653. }
  59654. else {
  59655. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  59656. }
  59657. }
  59658. else {
  59659. if (errorCallback) {
  59660. errorCallback();
  59661. }
  59662. }
  59663. });
  59664. };
  59665. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  59666. if (this.isSupported && this.db) {
  59667. var targetStore;
  59668. if (url.indexOf(".babylon") !== -1) {
  59669. targetStore = "scenes";
  59670. }
  59671. else {
  59672. targetStore = "textures";
  59673. }
  59674. var file;
  59675. var transaction = this.db.transaction([targetStore]);
  59676. transaction.oncomplete = function (event) {
  59677. if (file) {
  59678. callback(file.data);
  59679. }
  59680. else {
  59681. notInDBCallback();
  59682. }
  59683. };
  59684. transaction.onabort = function (event) {
  59685. notInDBCallback();
  59686. };
  59687. var getRequest = transaction.objectStore(targetStore).get(url);
  59688. getRequest.onsuccess = function (event) {
  59689. file = (event.target).result;
  59690. };
  59691. getRequest.onerror = function (event) {
  59692. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  59693. notInDBCallback();
  59694. };
  59695. }
  59696. else {
  59697. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59698. callback();
  59699. }
  59700. };
  59701. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  59702. var _this = this;
  59703. if (this.isSupported) {
  59704. var targetStore;
  59705. if (url.indexOf(".babylon") !== -1) {
  59706. targetStore = "scenes";
  59707. }
  59708. else {
  59709. targetStore = "textures";
  59710. }
  59711. // Create XHR
  59712. var xhr = new XMLHttpRequest();
  59713. var fileData;
  59714. xhr.open("GET", url, true);
  59715. if (useArrayBuffer) {
  59716. xhr.responseType = "arraybuffer";
  59717. }
  59718. if (progressCallback) {
  59719. xhr.onprogress = progressCallback;
  59720. }
  59721. xhr.addEventListener("load", function () {
  59722. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  59723. // Blob as response (XHR2)
  59724. //fileData = xhr.responseText;
  59725. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  59726. if (!_this.hasReachedQuota && _this.db) {
  59727. // Open a transaction to the database
  59728. var transaction = _this.db.transaction([targetStore], "readwrite");
  59729. // the transaction could abort because of a QuotaExceededError error
  59730. transaction.onabort = function (event) {
  59731. try {
  59732. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59733. var error = event.srcElement['error'];
  59734. if (error && error.name === "QuotaExceededError") {
  59735. _this.hasReachedQuota = true;
  59736. }
  59737. }
  59738. catch (ex) { }
  59739. callback(fileData);
  59740. };
  59741. transaction.oncomplete = function (event) {
  59742. callback(fileData);
  59743. };
  59744. var newFile;
  59745. if (targetStore === "scenes") {
  59746. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  59747. }
  59748. else {
  59749. newFile = { textureUrl: url, data: fileData };
  59750. }
  59751. try {
  59752. // Put the scene into the database
  59753. var addRequest = transaction.objectStore(targetStore).put(newFile);
  59754. addRequest.onsuccess = function (event) {
  59755. };
  59756. addRequest.onerror = function (event) {
  59757. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  59758. };
  59759. }
  59760. catch (ex) {
  59761. callback(fileData);
  59762. }
  59763. }
  59764. else {
  59765. callback(fileData);
  59766. }
  59767. }
  59768. else {
  59769. callback();
  59770. }
  59771. }, false);
  59772. xhr.addEventListener("error", function (event) {
  59773. BABYLON.Tools.Error("error on XHR request.");
  59774. callback();
  59775. }, false);
  59776. xhr.send();
  59777. }
  59778. else {
  59779. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59780. callback();
  59781. }
  59782. };
  59783. Database.IsUASupportingBlobStorage = true;
  59784. Database.IDBStorageEnabled = true;
  59785. Database.parseURL = function (url) {
  59786. var a = document.createElement('a');
  59787. a.href = url;
  59788. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  59789. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  59790. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  59791. return absLocation;
  59792. };
  59793. Database.ReturnFullUrlLocation = function (url) {
  59794. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  59795. return (Database.parseURL(window.location.href) + url);
  59796. }
  59797. else {
  59798. return url;
  59799. }
  59800. };
  59801. return Database;
  59802. }());
  59803. BABYLON.Database = Database;
  59804. })(BABYLON || (BABYLON = {}));
  59805. //# sourceMappingURL=babylon.database.js.map
  59806. var BABYLON;
  59807. (function (BABYLON) {
  59808. var FresnelParameters = /** @class */ (function () {
  59809. function FresnelParameters() {
  59810. this._isEnabled = true;
  59811. this.leftColor = BABYLON.Color3.White();
  59812. this.rightColor = BABYLON.Color3.Black();
  59813. this.bias = 0;
  59814. this.power = 1;
  59815. }
  59816. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  59817. get: function () {
  59818. return this._isEnabled;
  59819. },
  59820. set: function (value) {
  59821. if (this._isEnabled === value) {
  59822. return;
  59823. }
  59824. this._isEnabled = value;
  59825. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  59826. },
  59827. enumerable: true,
  59828. configurable: true
  59829. });
  59830. FresnelParameters.prototype.clone = function () {
  59831. var newFresnelParameters = new FresnelParameters();
  59832. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  59833. return newFresnelParameters;
  59834. };
  59835. FresnelParameters.prototype.serialize = function () {
  59836. var serializationObject = {};
  59837. serializationObject.isEnabled = this.isEnabled;
  59838. serializationObject.leftColor = this.leftColor;
  59839. serializationObject.rightColor = this.rightColor;
  59840. serializationObject.bias = this.bias;
  59841. serializationObject.power = this.power;
  59842. return serializationObject;
  59843. };
  59844. FresnelParameters.Parse = function (parsedFresnelParameters) {
  59845. var fresnelParameters = new FresnelParameters();
  59846. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  59847. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  59848. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  59849. fresnelParameters.bias = parsedFresnelParameters.bias;
  59850. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  59851. return fresnelParameters;
  59852. };
  59853. return FresnelParameters;
  59854. }());
  59855. BABYLON.FresnelParameters = FresnelParameters;
  59856. })(BABYLON || (BABYLON = {}));
  59857. //# sourceMappingURL=babylon.fresnelParameters.js.map
  59858. var BABYLON;
  59859. (function (BABYLON) {
  59860. var MultiMaterial = /** @class */ (function (_super) {
  59861. __extends(MultiMaterial, _super);
  59862. function MultiMaterial(name, scene) {
  59863. var _this = _super.call(this, name, scene, true) || this;
  59864. scene.multiMaterials.push(_this);
  59865. _this.subMaterials = new Array();
  59866. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  59867. return _this;
  59868. }
  59869. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  59870. get: function () {
  59871. return this._subMaterials;
  59872. },
  59873. set: function (value) {
  59874. this._subMaterials = value;
  59875. this._hookArray(value);
  59876. },
  59877. enumerable: true,
  59878. configurable: true
  59879. });
  59880. MultiMaterial.prototype._hookArray = function (array) {
  59881. var _this = this;
  59882. var oldPush = array.push;
  59883. array.push = function () {
  59884. var items = [];
  59885. for (var _i = 0; _i < arguments.length; _i++) {
  59886. items[_i] = arguments[_i];
  59887. }
  59888. var result = oldPush.apply(array, items);
  59889. _this._markAllSubMeshesAsTexturesDirty();
  59890. return result;
  59891. };
  59892. var oldSplice = array.splice;
  59893. array.splice = function (index, deleteCount) {
  59894. var deleted = oldSplice.apply(array, [index, deleteCount]);
  59895. _this._markAllSubMeshesAsTexturesDirty();
  59896. return deleted;
  59897. };
  59898. };
  59899. // Properties
  59900. MultiMaterial.prototype.getSubMaterial = function (index) {
  59901. if (index < 0 || index >= this.subMaterials.length) {
  59902. return this.getScene().defaultMaterial;
  59903. }
  59904. return this.subMaterials[index];
  59905. };
  59906. MultiMaterial.prototype.getActiveTextures = function () {
  59907. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  59908. if (subMaterial) {
  59909. return subMaterial.getActiveTextures();
  59910. }
  59911. else {
  59912. return [];
  59913. }
  59914. }));
  59915. var _a;
  59916. };
  59917. // Methods
  59918. MultiMaterial.prototype.getClassName = function () {
  59919. return "MultiMaterial";
  59920. };
  59921. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  59922. for (var index = 0; index < this.subMaterials.length; index++) {
  59923. var subMaterial = this.subMaterials[index];
  59924. if (subMaterial) {
  59925. if (subMaterial.storeEffectOnSubMeshes) {
  59926. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  59927. return false;
  59928. }
  59929. continue;
  59930. }
  59931. if (!subMaterial.isReady(mesh)) {
  59932. return false;
  59933. }
  59934. }
  59935. }
  59936. return true;
  59937. };
  59938. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  59939. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  59940. for (var index = 0; index < this.subMaterials.length; index++) {
  59941. var subMaterial = null;
  59942. var current = this.subMaterials[index];
  59943. if (cloneChildren && current) {
  59944. subMaterial = current.clone(name + "-" + current.name);
  59945. }
  59946. else {
  59947. subMaterial = this.subMaterials[index];
  59948. }
  59949. newMultiMaterial.subMaterials.push(subMaterial);
  59950. }
  59951. return newMultiMaterial;
  59952. };
  59953. MultiMaterial.prototype.serialize = function () {
  59954. var serializationObject = {};
  59955. serializationObject.name = this.name;
  59956. serializationObject.id = this.id;
  59957. if (BABYLON.Tags) {
  59958. serializationObject.tags = BABYLON.Tags.GetTags(this);
  59959. }
  59960. serializationObject.materials = [];
  59961. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  59962. var subMat = this.subMaterials[matIndex];
  59963. if (subMat) {
  59964. serializationObject.materials.push(subMat.id);
  59965. }
  59966. else {
  59967. serializationObject.materials.push(null);
  59968. }
  59969. }
  59970. return serializationObject;
  59971. };
  59972. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59973. var scene = this.getScene();
  59974. if (!scene) {
  59975. return;
  59976. }
  59977. var index = scene.multiMaterials.indexOf(this);
  59978. if (index >= 0) {
  59979. scene.multiMaterials.splice(index, 1);
  59980. }
  59981. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59982. };
  59983. return MultiMaterial;
  59984. }(BABYLON.Material));
  59985. BABYLON.MultiMaterial = MultiMaterial;
  59986. })(BABYLON || (BABYLON = {}));
  59987. //# sourceMappingURL=babylon.multiMaterial.js.map
  59988. var BABYLON;
  59989. (function (BABYLON) {
  59990. var FreeCameraTouchInput = /** @class */ (function () {
  59991. function FreeCameraTouchInput() {
  59992. this._offsetX = null;
  59993. this._offsetY = null;
  59994. this._pointerPressed = new Array();
  59995. this.touchAngularSensibility = 200000.0;
  59996. this.touchMoveSensibility = 250.0;
  59997. }
  59998. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  59999. var _this = this;
  60000. var previousPosition = null;
  60001. if (this._pointerInput === undefined) {
  60002. this._onLostFocus = function (evt) {
  60003. _this._offsetX = null;
  60004. _this._offsetY = null;
  60005. };
  60006. this._pointerInput = function (p, s) {
  60007. var evt = p.event;
  60008. if (evt.pointerType === "mouse") {
  60009. return;
  60010. }
  60011. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  60012. if (!noPreventDefault) {
  60013. evt.preventDefault();
  60014. }
  60015. _this._pointerPressed.push(evt.pointerId);
  60016. if (_this._pointerPressed.length !== 1) {
  60017. return;
  60018. }
  60019. previousPosition = {
  60020. x: evt.clientX,
  60021. y: evt.clientY
  60022. };
  60023. }
  60024. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  60025. if (!noPreventDefault) {
  60026. evt.preventDefault();
  60027. }
  60028. var index = _this._pointerPressed.indexOf(evt.pointerId);
  60029. if (index === -1) {
  60030. return;
  60031. }
  60032. _this._pointerPressed.splice(index, 1);
  60033. if (index != 0) {
  60034. return;
  60035. }
  60036. previousPosition = null;
  60037. _this._offsetX = null;
  60038. _this._offsetY = null;
  60039. }
  60040. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  60041. if (!noPreventDefault) {
  60042. evt.preventDefault();
  60043. }
  60044. if (!previousPosition) {
  60045. return;
  60046. }
  60047. var index = _this._pointerPressed.indexOf(evt.pointerId);
  60048. if (index != 0) {
  60049. return;
  60050. }
  60051. _this._offsetX = evt.clientX - previousPosition.x;
  60052. _this._offsetY = -(evt.clientY - previousPosition.y);
  60053. }
  60054. };
  60055. }
  60056. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  60057. if (this._onLostFocus) {
  60058. element.addEventListener("blur", this._onLostFocus);
  60059. }
  60060. };
  60061. FreeCameraTouchInput.prototype.detachControl = function (element) {
  60062. if (this._pointerInput && element) {
  60063. if (this._observer) {
  60064. this.camera.getScene().onPointerObservable.remove(this._observer);
  60065. this._observer = null;
  60066. }
  60067. if (this._onLostFocus) {
  60068. element.removeEventListener("blur", this._onLostFocus);
  60069. this._onLostFocus = null;
  60070. }
  60071. this._pointerPressed = [];
  60072. this._offsetX = null;
  60073. this._offsetY = null;
  60074. }
  60075. };
  60076. FreeCameraTouchInput.prototype.checkInputs = function () {
  60077. if (this._offsetX && this._offsetY) {
  60078. var camera = this.camera;
  60079. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  60080. if (this._pointerPressed.length > 1) {
  60081. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  60082. }
  60083. else {
  60084. var speed = camera._computeLocalCameraSpeed();
  60085. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  60086. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  60087. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  60088. }
  60089. }
  60090. };
  60091. FreeCameraTouchInput.prototype.getClassName = function () {
  60092. return "FreeCameraTouchInput";
  60093. };
  60094. FreeCameraTouchInput.prototype.getSimpleName = function () {
  60095. return "touch";
  60096. };
  60097. __decorate([
  60098. BABYLON.serialize()
  60099. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  60100. __decorate([
  60101. BABYLON.serialize()
  60102. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  60103. return FreeCameraTouchInput;
  60104. }());
  60105. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  60106. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  60107. })(BABYLON || (BABYLON = {}));
  60108. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  60109. var BABYLON;
  60110. (function (BABYLON) {
  60111. // We're mainly based on the logic defined into the FreeCamera code
  60112. var TouchCamera = /** @class */ (function (_super) {
  60113. __extends(TouchCamera, _super);
  60114. //-- end properties for backward compatibility for inputs
  60115. function TouchCamera(name, position, scene) {
  60116. var _this = _super.call(this, name, position, scene) || this;
  60117. _this.inputs.addTouch();
  60118. _this._setupInputs();
  60119. return _this;
  60120. }
  60121. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  60122. //-- Begin properties for backward compatibility for inputs
  60123. get: function () {
  60124. var touch = this.inputs.attached["touch"];
  60125. if (touch)
  60126. return touch.touchAngularSensibility;
  60127. return 0;
  60128. },
  60129. set: function (value) {
  60130. var touch = this.inputs.attached["touch"];
  60131. if (touch)
  60132. touch.touchAngularSensibility = value;
  60133. },
  60134. enumerable: true,
  60135. configurable: true
  60136. });
  60137. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  60138. get: function () {
  60139. var touch = this.inputs.attached["touch"];
  60140. if (touch)
  60141. return touch.touchMoveSensibility;
  60142. return 0;
  60143. },
  60144. set: function (value) {
  60145. var touch = this.inputs.attached["touch"];
  60146. if (touch)
  60147. touch.touchMoveSensibility = value;
  60148. },
  60149. enumerable: true,
  60150. configurable: true
  60151. });
  60152. TouchCamera.prototype.getClassName = function () {
  60153. return "TouchCamera";
  60154. };
  60155. TouchCamera.prototype._setupInputs = function () {
  60156. var mouse = this.inputs.attached["mouse"];
  60157. if (mouse) {
  60158. mouse.touchEnabled = false;
  60159. }
  60160. };
  60161. return TouchCamera;
  60162. }(BABYLON.FreeCamera));
  60163. BABYLON.TouchCamera = TouchCamera;
  60164. })(BABYLON || (BABYLON = {}));
  60165. //# sourceMappingURL=babylon.touchCamera.js.map
  60166. var BABYLON;
  60167. (function (BABYLON) {
  60168. var ProceduralTexture = /** @class */ (function (_super) {
  60169. __extends(ProceduralTexture, _super);
  60170. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  60171. if (fallbackTexture === void 0) { fallbackTexture = null; }
  60172. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60173. if (isCube === void 0) { isCube = false; }
  60174. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  60175. _this.isCube = isCube;
  60176. _this.isEnabled = true;
  60177. _this._currentRefreshId = -1;
  60178. _this._refreshRate = 1;
  60179. _this._vertexBuffers = {};
  60180. _this._uniforms = new Array();
  60181. _this._samplers = new Array();
  60182. _this._textures = {};
  60183. _this._floats = {};
  60184. _this._floatsArrays = {};
  60185. _this._colors3 = {};
  60186. _this._colors4 = {};
  60187. _this._vectors2 = {};
  60188. _this._vectors3 = {};
  60189. _this._matrices = {};
  60190. _this._fallbackTextureUsed = false;
  60191. scene._proceduralTextures.push(_this);
  60192. _this._engine = scene.getEngine();
  60193. _this.name = name;
  60194. _this.isRenderTarget = true;
  60195. _this._size = size;
  60196. _this._generateMipMaps = generateMipMaps;
  60197. _this.setFragment(fragment);
  60198. _this._fallbackTexture = fallbackTexture;
  60199. if (isCube) {
  60200. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  60201. _this.setFloat("face", 0);
  60202. }
  60203. else {
  60204. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  60205. }
  60206. // VBO
  60207. var vertices = [];
  60208. vertices.push(1, 1);
  60209. vertices.push(-1, 1);
  60210. vertices.push(-1, -1);
  60211. vertices.push(1, -1);
  60212. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60213. _this._createIndexBuffer();
  60214. return _this;
  60215. }
  60216. ProceduralTexture.prototype._createIndexBuffer = function () {
  60217. var engine = this._engine;
  60218. // Indices
  60219. var indices = [];
  60220. indices.push(0);
  60221. indices.push(1);
  60222. indices.push(2);
  60223. indices.push(0);
  60224. indices.push(2);
  60225. indices.push(3);
  60226. this._indexBuffer = engine.createIndexBuffer(indices);
  60227. };
  60228. ProceduralTexture.prototype._rebuild = function () {
  60229. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60230. if (vb) {
  60231. vb._rebuild();
  60232. }
  60233. this._createIndexBuffer();
  60234. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  60235. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  60236. }
  60237. };
  60238. ProceduralTexture.prototype.reset = function () {
  60239. if (this._effect === undefined) {
  60240. return;
  60241. }
  60242. var engine = this._engine;
  60243. engine._releaseEffect(this._effect);
  60244. };
  60245. ProceduralTexture.prototype.isReady = function () {
  60246. var _this = this;
  60247. var engine = this._engine;
  60248. var shaders;
  60249. if (!this._fragment) {
  60250. return false;
  60251. }
  60252. if (this._fallbackTextureUsed) {
  60253. return true;
  60254. }
  60255. if (this._fragment.fragmentElement !== undefined) {
  60256. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  60257. }
  60258. else {
  60259. shaders = { vertex: "procedural", fragment: this._fragment };
  60260. }
  60261. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  60262. _this.releaseInternalTexture();
  60263. if (_this._fallbackTexture) {
  60264. _this._texture = _this._fallbackTexture._texture;
  60265. if (_this._texture) {
  60266. _this._texture.incrementReferences();
  60267. }
  60268. }
  60269. _this._fallbackTextureUsed = true;
  60270. });
  60271. return this._effect.isReady();
  60272. };
  60273. ProceduralTexture.prototype.resetRefreshCounter = function () {
  60274. this._currentRefreshId = -1;
  60275. };
  60276. ProceduralTexture.prototype.setFragment = function (fragment) {
  60277. this._fragment = fragment;
  60278. };
  60279. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  60280. get: function () {
  60281. return this._refreshRate;
  60282. },
  60283. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  60284. set: function (value) {
  60285. this._refreshRate = value;
  60286. this.resetRefreshCounter();
  60287. },
  60288. enumerable: true,
  60289. configurable: true
  60290. });
  60291. ProceduralTexture.prototype._shouldRender = function () {
  60292. if (!this.isEnabled || !this.isReady() || !this._texture) {
  60293. return false;
  60294. }
  60295. if (this._fallbackTextureUsed) {
  60296. return false;
  60297. }
  60298. if (this._currentRefreshId === -1) {
  60299. this._currentRefreshId = 1;
  60300. return true;
  60301. }
  60302. if (this.refreshRate === this._currentRefreshId) {
  60303. this._currentRefreshId = 1;
  60304. return true;
  60305. }
  60306. this._currentRefreshId++;
  60307. return false;
  60308. };
  60309. ProceduralTexture.prototype.getRenderSize = function () {
  60310. return this._size;
  60311. };
  60312. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  60313. if (this._fallbackTextureUsed) {
  60314. return;
  60315. }
  60316. this.releaseInternalTexture();
  60317. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  60318. };
  60319. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  60320. if (this._uniforms.indexOf(uniformName) === -1) {
  60321. this._uniforms.push(uniformName);
  60322. }
  60323. };
  60324. ProceduralTexture.prototype.setTexture = function (name, texture) {
  60325. if (this._samplers.indexOf(name) === -1) {
  60326. this._samplers.push(name);
  60327. }
  60328. this._textures[name] = texture;
  60329. return this;
  60330. };
  60331. ProceduralTexture.prototype.setFloat = function (name, value) {
  60332. this._checkUniform(name);
  60333. this._floats[name] = value;
  60334. return this;
  60335. };
  60336. ProceduralTexture.prototype.setFloats = function (name, value) {
  60337. this._checkUniform(name);
  60338. this._floatsArrays[name] = value;
  60339. return this;
  60340. };
  60341. ProceduralTexture.prototype.setColor3 = function (name, value) {
  60342. this._checkUniform(name);
  60343. this._colors3[name] = value;
  60344. return this;
  60345. };
  60346. ProceduralTexture.prototype.setColor4 = function (name, value) {
  60347. this._checkUniform(name);
  60348. this._colors4[name] = value;
  60349. return this;
  60350. };
  60351. ProceduralTexture.prototype.setVector2 = function (name, value) {
  60352. this._checkUniform(name);
  60353. this._vectors2[name] = value;
  60354. return this;
  60355. };
  60356. ProceduralTexture.prototype.setVector3 = function (name, value) {
  60357. this._checkUniform(name);
  60358. this._vectors3[name] = value;
  60359. return this;
  60360. };
  60361. ProceduralTexture.prototype.setMatrix = function (name, value) {
  60362. this._checkUniform(name);
  60363. this._matrices[name] = value;
  60364. return this;
  60365. };
  60366. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60367. var scene = this.getScene();
  60368. if (!scene) {
  60369. return;
  60370. }
  60371. var engine = this._engine;
  60372. // Render
  60373. engine.enableEffect(this._effect);
  60374. engine.setState(false);
  60375. // Texture
  60376. for (var name in this._textures) {
  60377. this._effect.setTexture(name, this._textures[name]);
  60378. }
  60379. // Float
  60380. for (name in this._floats) {
  60381. this._effect.setFloat(name, this._floats[name]);
  60382. }
  60383. // Floats
  60384. for (name in this._floatsArrays) {
  60385. this._effect.setArray(name, this._floatsArrays[name]);
  60386. }
  60387. // Color3
  60388. for (name in this._colors3) {
  60389. this._effect.setColor3(name, this._colors3[name]);
  60390. }
  60391. // Color4
  60392. for (name in this._colors4) {
  60393. var color = this._colors4[name];
  60394. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60395. }
  60396. // Vector2
  60397. for (name in this._vectors2) {
  60398. this._effect.setVector2(name, this._vectors2[name]);
  60399. }
  60400. // Vector3
  60401. for (name in this._vectors3) {
  60402. this._effect.setVector3(name, this._vectors3[name]);
  60403. }
  60404. // Matrix
  60405. for (name in this._matrices) {
  60406. this._effect.setMatrix(name, this._matrices[name]);
  60407. }
  60408. if (!this._texture) {
  60409. return;
  60410. }
  60411. if (this.isCube) {
  60412. for (var face = 0; face < 6; face++) {
  60413. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  60414. // VBOs
  60415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60416. this._effect.setFloat("face", face);
  60417. // Clear
  60418. engine.clear(scene.clearColor, true, true, true);
  60419. // Draw order
  60420. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60421. // Mipmaps
  60422. if (face === 5) {
  60423. engine.generateMipMapsForCubemap(this._texture);
  60424. }
  60425. }
  60426. }
  60427. else {
  60428. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  60429. // VBOs
  60430. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60431. // Clear
  60432. engine.clear(scene.clearColor, true, true, true);
  60433. // Draw order
  60434. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60435. }
  60436. // Unbind
  60437. engine.unBindFramebuffer(this._texture, this.isCube);
  60438. if (this.onGenerated) {
  60439. this.onGenerated();
  60440. }
  60441. };
  60442. ProceduralTexture.prototype.clone = function () {
  60443. var textureSize = this.getSize();
  60444. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  60445. // Base texture
  60446. newTexture.hasAlpha = this.hasAlpha;
  60447. newTexture.level = this.level;
  60448. // RenderTarget Texture
  60449. newTexture.coordinatesMode = this.coordinatesMode;
  60450. return newTexture;
  60451. };
  60452. ProceduralTexture.prototype.dispose = function () {
  60453. var scene = this.getScene();
  60454. if (!scene) {
  60455. return;
  60456. }
  60457. var index = scene._proceduralTextures.indexOf(this);
  60458. if (index >= 0) {
  60459. scene._proceduralTextures.splice(index, 1);
  60460. }
  60461. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60462. if (vertexBuffer) {
  60463. vertexBuffer.dispose();
  60464. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60465. }
  60466. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  60467. this._indexBuffer = null;
  60468. }
  60469. _super.prototype.dispose.call(this);
  60470. };
  60471. return ProceduralTexture;
  60472. }(BABYLON.Texture));
  60473. BABYLON.ProceduralTexture = ProceduralTexture;
  60474. })(BABYLON || (BABYLON = {}));
  60475. //# sourceMappingURL=babylon.proceduralTexture.js.map
  60476. var BABYLON;
  60477. (function (BABYLON) {
  60478. var CustomProceduralTexture = /** @class */ (function (_super) {
  60479. __extends(CustomProceduralTexture, _super);
  60480. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  60481. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  60482. _this._animate = true;
  60483. _this._time = 0;
  60484. _this._texturePath = texturePath;
  60485. //Try to load json
  60486. _this.loadJson(texturePath);
  60487. _this.refreshRate = 1;
  60488. return _this;
  60489. }
  60490. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  60491. var _this = this;
  60492. var noConfigFile = function () {
  60493. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  60494. try {
  60495. _this.setFragment(_this._texturePath);
  60496. }
  60497. catch (ex) {
  60498. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  60499. }
  60500. };
  60501. var configFileUrl = jsonUrl + "/config.json";
  60502. var xhr = new XMLHttpRequest();
  60503. xhr.open("GET", configFileUrl, true);
  60504. xhr.addEventListener("load", function () {
  60505. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60506. try {
  60507. _this._config = JSON.parse(xhr.response);
  60508. _this.updateShaderUniforms();
  60509. _this.updateTextures();
  60510. _this.setFragment(_this._texturePath + "/custom");
  60511. _this._animate = _this._config.animate;
  60512. _this.refreshRate = _this._config.refreshrate;
  60513. }
  60514. catch (ex) {
  60515. noConfigFile();
  60516. }
  60517. }
  60518. else {
  60519. noConfigFile();
  60520. }
  60521. }, false);
  60522. xhr.addEventListener("error", function () {
  60523. noConfigFile();
  60524. }, false);
  60525. try {
  60526. xhr.send();
  60527. }
  60528. catch (ex) {
  60529. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  60530. }
  60531. };
  60532. CustomProceduralTexture.prototype.isReady = function () {
  60533. if (!_super.prototype.isReady.call(this)) {
  60534. return false;
  60535. }
  60536. for (var name in this._textures) {
  60537. var texture = this._textures[name];
  60538. if (!texture.isReady()) {
  60539. return false;
  60540. }
  60541. }
  60542. return true;
  60543. };
  60544. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60545. var scene = this.getScene();
  60546. if (this._animate && scene) {
  60547. this._time += scene.getAnimationRatio() * 0.03;
  60548. this.updateShaderUniforms();
  60549. }
  60550. _super.prototype.render.call(this, useCameraPostProcess);
  60551. };
  60552. CustomProceduralTexture.prototype.updateTextures = function () {
  60553. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  60554. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  60555. }
  60556. };
  60557. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  60558. if (this._config) {
  60559. for (var j = 0; j < this._config.uniforms.length; j++) {
  60560. var uniform = this._config.uniforms[j];
  60561. switch (uniform.type) {
  60562. case "float":
  60563. this.setFloat(uniform.name, uniform.value);
  60564. break;
  60565. case "color3":
  60566. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  60567. break;
  60568. case "color4":
  60569. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  60570. break;
  60571. case "vector2":
  60572. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  60573. break;
  60574. case "vector3":
  60575. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  60576. break;
  60577. }
  60578. }
  60579. }
  60580. this.setFloat("time", this._time);
  60581. };
  60582. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  60583. get: function () {
  60584. return this._animate;
  60585. },
  60586. set: function (value) {
  60587. this._animate = value;
  60588. },
  60589. enumerable: true,
  60590. configurable: true
  60591. });
  60592. return CustomProceduralTexture;
  60593. }(BABYLON.ProceduralTexture));
  60594. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  60595. })(BABYLON || (BABYLON = {}));
  60596. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  60597. var BABYLON;
  60598. (function (BABYLON) {
  60599. var FreeCameraGamepadInput = /** @class */ (function () {
  60600. function FreeCameraGamepadInput() {
  60601. this.gamepadAngularSensibility = 200;
  60602. this.gamepadMoveSensibility = 40;
  60603. // private members
  60604. this._cameraTransform = BABYLON.Matrix.Identity();
  60605. this._deltaTransform = BABYLON.Vector3.Zero();
  60606. this._vector3 = BABYLON.Vector3.Zero();
  60607. this._vector2 = BABYLON.Vector2.Zero();
  60608. }
  60609. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60610. var _this = this;
  60611. var manager = this.camera.getScene().gamepadManager;
  60612. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60613. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60614. // prioritize XBOX gamepads.
  60615. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60616. _this.gamepad = gamepad;
  60617. }
  60618. }
  60619. });
  60620. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60621. if (_this.gamepad === gamepad) {
  60622. _this.gamepad = null;
  60623. }
  60624. });
  60625. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60626. };
  60627. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  60628. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60629. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60630. this.gamepad = null;
  60631. };
  60632. FreeCameraGamepadInput.prototype.checkInputs = function () {
  60633. if (this.gamepad && this.gamepad.leftStick) {
  60634. var camera = this.camera;
  60635. var LSValues = this.gamepad.leftStick;
  60636. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  60637. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60638. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  60639. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  60640. var RSValues = this.gamepad.rightStick;
  60641. if (RSValues) {
  60642. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  60643. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  60644. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  60645. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  60646. }
  60647. else {
  60648. RSValues = { x: 0, y: 0 };
  60649. }
  60650. if (!camera.rotationQuaternion) {
  60651. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  60652. }
  60653. else {
  60654. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  60655. }
  60656. var speed = camera._computeLocalCameraSpeed() * 50.0;
  60657. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  60658. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  60659. camera.cameraDirection.addInPlace(this._deltaTransform);
  60660. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  60661. camera.cameraRotation.addInPlace(this._vector2);
  60662. }
  60663. };
  60664. FreeCameraGamepadInput.prototype.getClassName = function () {
  60665. return "FreeCameraGamepadInput";
  60666. };
  60667. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  60668. return "gamepad";
  60669. };
  60670. __decorate([
  60671. BABYLON.serialize()
  60672. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  60673. __decorate([
  60674. BABYLON.serialize()
  60675. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60676. return FreeCameraGamepadInput;
  60677. }());
  60678. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  60679. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  60680. })(BABYLON || (BABYLON = {}));
  60681. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  60682. var BABYLON;
  60683. (function (BABYLON) {
  60684. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  60685. function ArcRotateCameraGamepadInput() {
  60686. this.gamepadRotationSensibility = 80;
  60687. this.gamepadMoveSensibility = 40;
  60688. }
  60689. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60690. var _this = this;
  60691. var manager = this.camera.getScene().gamepadManager;
  60692. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60693. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60694. // prioritize XBOX gamepads.
  60695. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60696. _this.gamepad = gamepad;
  60697. }
  60698. }
  60699. });
  60700. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60701. if (_this.gamepad === gamepad) {
  60702. _this.gamepad = null;
  60703. }
  60704. });
  60705. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60706. };
  60707. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  60708. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60709. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60710. this.gamepad = null;
  60711. };
  60712. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  60713. if (this.gamepad) {
  60714. var camera = this.camera;
  60715. var RSValues = this.gamepad.rightStick;
  60716. if (RSValues) {
  60717. if (RSValues.x != 0) {
  60718. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  60719. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  60720. camera.inertialAlphaOffset += normalizedRX;
  60721. }
  60722. }
  60723. if (RSValues.y != 0) {
  60724. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  60725. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  60726. camera.inertialBetaOffset += normalizedRY;
  60727. }
  60728. }
  60729. }
  60730. var LSValues = this.gamepad.leftStick;
  60731. if (LSValues && LSValues.y != 0) {
  60732. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60733. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  60734. this.camera.inertialRadiusOffset -= normalizedLY;
  60735. }
  60736. }
  60737. }
  60738. };
  60739. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  60740. return "ArcRotateCameraGamepadInput";
  60741. };
  60742. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  60743. return "gamepad";
  60744. };
  60745. __decorate([
  60746. BABYLON.serialize()
  60747. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  60748. __decorate([
  60749. BABYLON.serialize()
  60750. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60751. return ArcRotateCameraGamepadInput;
  60752. }());
  60753. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  60754. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  60755. })(BABYLON || (BABYLON = {}));
  60756. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  60757. var BABYLON;
  60758. (function (BABYLON) {
  60759. var GamepadManager = /** @class */ (function () {
  60760. function GamepadManager(_scene) {
  60761. var _this = this;
  60762. this._scene = _scene;
  60763. this._babylonGamepads = [];
  60764. this._oneGamepadConnected = false;
  60765. this._isMonitoring = false;
  60766. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  60767. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60768. this._gamepadEventSupported = false;
  60769. }
  60770. else {
  60771. this._gamepadEventSupported = 'GamepadEvent' in window;
  60772. this._gamepadSupport = (navigator.getGamepads ||
  60773. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  60774. }
  60775. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  60776. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  60777. for (var i in _this._babylonGamepads) {
  60778. var gamepad = _this._babylonGamepads[i];
  60779. if (gamepad && gamepad._isConnected) {
  60780. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  60781. }
  60782. }
  60783. });
  60784. this._onGamepadConnectedEvent = function (evt) {
  60785. var gamepad = evt.gamepad;
  60786. if (gamepad.index in _this._babylonGamepads) {
  60787. if (_this._babylonGamepads[gamepad.index].isConnected) {
  60788. return;
  60789. }
  60790. }
  60791. var newGamepad;
  60792. if (_this._babylonGamepads[gamepad.index]) {
  60793. newGamepad = _this._babylonGamepads[gamepad.index];
  60794. newGamepad.browserGamepad = gamepad;
  60795. newGamepad._isConnected = true;
  60796. }
  60797. else {
  60798. newGamepad = _this._addNewGamepad(gamepad);
  60799. }
  60800. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60801. _this._startMonitoringGamepads();
  60802. };
  60803. this._onGamepadDisconnectedEvent = function (evt) {
  60804. var gamepad = evt.gamepad;
  60805. // Remove the gamepad from the list of gamepads to monitor.
  60806. for (var i in _this._babylonGamepads) {
  60807. if (_this._babylonGamepads[i].index === gamepad.index) {
  60808. var disconnectedGamepad = _this._babylonGamepads[i];
  60809. disconnectedGamepad._isConnected = false;
  60810. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  60811. break;
  60812. }
  60813. }
  60814. };
  60815. if (this._gamepadSupport) {
  60816. //first add already-connected gamepads
  60817. this._updateGamepadObjects();
  60818. if (this._babylonGamepads.length) {
  60819. this._startMonitoringGamepads();
  60820. }
  60821. // Checking if the gamepad connected event is supported (like in Firefox)
  60822. if (this._gamepadEventSupported) {
  60823. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  60824. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  60825. }
  60826. else {
  60827. this._startMonitoringGamepads();
  60828. }
  60829. }
  60830. }
  60831. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  60832. get: function () {
  60833. return this._babylonGamepads;
  60834. },
  60835. enumerable: true,
  60836. configurable: true
  60837. });
  60838. GamepadManager.prototype.getGamepadByType = function (type) {
  60839. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  60840. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  60841. var gamepad = _a[_i];
  60842. if (gamepad && gamepad.type === type) {
  60843. return gamepad;
  60844. }
  60845. }
  60846. return null;
  60847. };
  60848. GamepadManager.prototype.dispose = function () {
  60849. if (this._gamepadEventSupported) {
  60850. if (this._onGamepadConnectedEvent) {
  60851. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  60852. }
  60853. if (this._onGamepadDisconnectedEvent) {
  60854. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  60855. }
  60856. this._onGamepadConnectedEvent = null;
  60857. this._onGamepadDisconnectedEvent = null;
  60858. }
  60859. this._babylonGamepads.forEach(function (gamepad) {
  60860. gamepad.dispose();
  60861. });
  60862. this.onGamepadConnectedObservable.clear();
  60863. this.onGamepadDisconnectedObservable.clear();
  60864. this._oneGamepadConnected = false;
  60865. this._stopMonitoringGamepads();
  60866. this._babylonGamepads = [];
  60867. };
  60868. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  60869. if (!this._oneGamepadConnected) {
  60870. this._oneGamepadConnected = true;
  60871. }
  60872. var newGamepad;
  60873. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  60874. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  60875. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  60876. }
  60877. else if (gamepad.pose) {
  60878. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  60879. }
  60880. else {
  60881. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  60882. }
  60883. this._babylonGamepads[newGamepad.index] = newGamepad;
  60884. return newGamepad;
  60885. };
  60886. GamepadManager.prototype._startMonitoringGamepads = function () {
  60887. if (!this._isMonitoring) {
  60888. this._isMonitoring = true;
  60889. //back-comp
  60890. if (!this._scene) {
  60891. this._checkGamepadsStatus();
  60892. }
  60893. }
  60894. };
  60895. GamepadManager.prototype._stopMonitoringGamepads = function () {
  60896. this._isMonitoring = false;
  60897. };
  60898. GamepadManager.prototype._checkGamepadsStatus = function () {
  60899. var _this = this;
  60900. // Hack to be compatible Chrome
  60901. this._updateGamepadObjects();
  60902. for (var i in this._babylonGamepads) {
  60903. var gamepad = this._babylonGamepads[i];
  60904. if (!gamepad || !gamepad.isConnected) {
  60905. continue;
  60906. }
  60907. gamepad.update();
  60908. }
  60909. if (this._isMonitoring && !this._scene) {
  60910. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  60911. }
  60912. };
  60913. // This function is called only on Chrome, which does not properly support
  60914. // connection/disconnection events and forces you to recopy again the gamepad object
  60915. GamepadManager.prototype._updateGamepadObjects = function () {
  60916. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  60917. for (var i = 0; i < gamepads.length; i++) {
  60918. if (gamepads[i]) {
  60919. if (!this._babylonGamepads[gamepads[i].index]) {
  60920. var newGamepad = this._addNewGamepad(gamepads[i]);
  60921. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60922. }
  60923. else {
  60924. // Forced to copy again this object for Chrome for unknown reason
  60925. this._babylonGamepads[i].browserGamepad = gamepads[i];
  60926. if (!this._babylonGamepads[i].isConnected) {
  60927. this._babylonGamepads[i]._isConnected = true;
  60928. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  60929. }
  60930. }
  60931. }
  60932. }
  60933. };
  60934. return GamepadManager;
  60935. }());
  60936. BABYLON.GamepadManager = GamepadManager;
  60937. })(BABYLON || (BABYLON = {}));
  60938. //# sourceMappingURL=babylon.gamepadManager.js.map
  60939. var BABYLON;
  60940. (function (BABYLON) {
  60941. var StickValues = /** @class */ (function () {
  60942. function StickValues(x, y) {
  60943. this.x = x;
  60944. this.y = y;
  60945. }
  60946. return StickValues;
  60947. }());
  60948. BABYLON.StickValues = StickValues;
  60949. var Gamepad = /** @class */ (function () {
  60950. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  60951. if (leftStickX === void 0) { leftStickX = 0; }
  60952. if (leftStickY === void 0) { leftStickY = 1; }
  60953. if (rightStickX === void 0) { rightStickX = 2; }
  60954. if (rightStickY === void 0) { rightStickY = 3; }
  60955. this.id = id;
  60956. this.index = index;
  60957. this.browserGamepad = browserGamepad;
  60958. this._isConnected = true;
  60959. this._invertLeftStickY = false;
  60960. this.type = Gamepad.GAMEPAD;
  60961. this._leftStickAxisX = leftStickX;
  60962. this._leftStickAxisY = leftStickY;
  60963. this._rightStickAxisX = rightStickX;
  60964. this._rightStickAxisY = rightStickY;
  60965. if (this.browserGamepad.axes.length >= 2) {
  60966. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60967. }
  60968. if (this.browserGamepad.axes.length >= 4) {
  60969. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60970. }
  60971. }
  60972. Object.defineProperty(Gamepad.prototype, "isConnected", {
  60973. get: function () {
  60974. return this._isConnected;
  60975. },
  60976. enumerable: true,
  60977. configurable: true
  60978. });
  60979. Gamepad.prototype.onleftstickchanged = function (callback) {
  60980. this._onleftstickchanged = callback;
  60981. };
  60982. Gamepad.prototype.onrightstickchanged = function (callback) {
  60983. this._onrightstickchanged = callback;
  60984. };
  60985. Object.defineProperty(Gamepad.prototype, "leftStick", {
  60986. get: function () {
  60987. return this._leftStick;
  60988. },
  60989. set: function (newValues) {
  60990. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  60991. this._onleftstickchanged(newValues);
  60992. }
  60993. this._leftStick = newValues;
  60994. },
  60995. enumerable: true,
  60996. configurable: true
  60997. });
  60998. Object.defineProperty(Gamepad.prototype, "rightStick", {
  60999. get: function () {
  61000. return this._rightStick;
  61001. },
  61002. set: function (newValues) {
  61003. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  61004. this._onrightstickchanged(newValues);
  61005. }
  61006. this._rightStick = newValues;
  61007. },
  61008. enumerable: true,
  61009. configurable: true
  61010. });
  61011. Gamepad.prototype.update = function () {
  61012. if (this._leftStick) {
  61013. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  61014. if (this._invertLeftStickY) {
  61015. this.leftStick.y *= -1;
  61016. }
  61017. }
  61018. if (this._rightStick) {
  61019. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  61020. }
  61021. };
  61022. Gamepad.prototype.dispose = function () {
  61023. };
  61024. Gamepad.GAMEPAD = 0;
  61025. Gamepad.GENERIC = 1;
  61026. Gamepad.XBOX = 2;
  61027. Gamepad.POSE_ENABLED = 3;
  61028. return Gamepad;
  61029. }());
  61030. BABYLON.Gamepad = Gamepad;
  61031. var GenericPad = /** @class */ (function (_super) {
  61032. __extends(GenericPad, _super);
  61033. function GenericPad(id, index, browserGamepad) {
  61034. var _this = _super.call(this, id, index, browserGamepad) || this;
  61035. _this.onButtonDownObservable = new BABYLON.Observable();
  61036. _this.onButtonUpObservable = new BABYLON.Observable();
  61037. _this.type = Gamepad.GENERIC;
  61038. _this._buttons = new Array(browserGamepad.buttons.length);
  61039. return _this;
  61040. }
  61041. GenericPad.prototype.onbuttondown = function (callback) {
  61042. this._onbuttondown = callback;
  61043. };
  61044. GenericPad.prototype.onbuttonup = function (callback) {
  61045. this._onbuttonup = callback;
  61046. };
  61047. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  61048. if (newValue !== currentValue) {
  61049. if (newValue === 1) {
  61050. if (this._onbuttondown) {
  61051. this._onbuttondown(buttonIndex);
  61052. }
  61053. this.onButtonDownObservable.notifyObservers(buttonIndex);
  61054. }
  61055. if (newValue === 0) {
  61056. if (this._onbuttonup) {
  61057. this._onbuttonup(buttonIndex);
  61058. }
  61059. this.onButtonUpObservable.notifyObservers(buttonIndex);
  61060. }
  61061. }
  61062. return newValue;
  61063. };
  61064. GenericPad.prototype.update = function () {
  61065. _super.prototype.update.call(this);
  61066. for (var index = 0; index < this._buttons.length; index++) {
  61067. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  61068. }
  61069. };
  61070. GenericPad.prototype.dispose = function () {
  61071. _super.prototype.dispose.call(this);
  61072. this.onButtonDownObservable.clear();
  61073. this.onButtonUpObservable.clear();
  61074. };
  61075. return GenericPad;
  61076. }(Gamepad));
  61077. BABYLON.GenericPad = GenericPad;
  61078. })(BABYLON || (BABYLON = {}));
  61079. //# sourceMappingURL=babylon.gamepad.js.map
  61080. var BABYLON;
  61081. (function (BABYLON) {
  61082. var Xbox360Button;
  61083. (function (Xbox360Button) {
  61084. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  61085. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  61086. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  61087. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  61088. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  61089. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  61090. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  61091. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  61092. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  61093. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  61094. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  61095. var Xbox360Dpad;
  61096. (function (Xbox360Dpad) {
  61097. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  61098. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  61099. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  61100. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  61101. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  61102. var Xbox360Pad = /** @class */ (function (_super) {
  61103. __extends(Xbox360Pad, _super);
  61104. function Xbox360Pad(id, index, gamepad, xboxOne) {
  61105. if (xboxOne === void 0) { xboxOne = false; }
  61106. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  61107. _this._leftTrigger = 0;
  61108. _this._rightTrigger = 0;
  61109. _this.onButtonDownObservable = new BABYLON.Observable();
  61110. _this.onButtonUpObservable = new BABYLON.Observable();
  61111. _this.onPadDownObservable = new BABYLON.Observable();
  61112. _this.onPadUpObservable = new BABYLON.Observable();
  61113. _this._buttonA = 0;
  61114. _this._buttonB = 0;
  61115. _this._buttonX = 0;
  61116. _this._buttonY = 0;
  61117. _this._buttonBack = 0;
  61118. _this._buttonStart = 0;
  61119. _this._buttonLB = 0;
  61120. _this._buttonRB = 0;
  61121. _this._buttonLeftStick = 0;
  61122. _this._buttonRightStick = 0;
  61123. _this._dPadUp = 0;
  61124. _this._dPadDown = 0;
  61125. _this._dPadLeft = 0;
  61126. _this._dPadRight = 0;
  61127. _this._isXboxOnePad = false;
  61128. _this.type = BABYLON.Gamepad.XBOX;
  61129. _this._isXboxOnePad = xboxOne;
  61130. return _this;
  61131. }
  61132. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  61133. this._onlefttriggerchanged = callback;
  61134. };
  61135. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  61136. this._onrighttriggerchanged = callback;
  61137. };
  61138. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  61139. get: function () {
  61140. return this._leftTrigger;
  61141. },
  61142. set: function (newValue) {
  61143. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  61144. this._onlefttriggerchanged(newValue);
  61145. }
  61146. this._leftTrigger = newValue;
  61147. },
  61148. enumerable: true,
  61149. configurable: true
  61150. });
  61151. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  61152. get: function () {
  61153. return this._rightTrigger;
  61154. },
  61155. set: function (newValue) {
  61156. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  61157. this._onrighttriggerchanged(newValue);
  61158. }
  61159. this._rightTrigger = newValue;
  61160. },
  61161. enumerable: true,
  61162. configurable: true
  61163. });
  61164. Xbox360Pad.prototype.onbuttondown = function (callback) {
  61165. this._onbuttondown = callback;
  61166. };
  61167. Xbox360Pad.prototype.onbuttonup = function (callback) {
  61168. this._onbuttonup = callback;
  61169. };
  61170. Xbox360Pad.prototype.ondpaddown = function (callback) {
  61171. this._ondpaddown = callback;
  61172. };
  61173. Xbox360Pad.prototype.ondpadup = function (callback) {
  61174. this._ondpadup = callback;
  61175. };
  61176. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  61177. if (newValue !== currentValue) {
  61178. if (newValue === 1) {
  61179. if (this._onbuttondown) {
  61180. this._onbuttondown(buttonType);
  61181. }
  61182. this.onButtonDownObservable.notifyObservers(buttonType);
  61183. }
  61184. if (newValue === 0) {
  61185. if (this._onbuttonup) {
  61186. this._onbuttonup(buttonType);
  61187. }
  61188. this.onButtonUpObservable.notifyObservers(buttonType);
  61189. }
  61190. }
  61191. return newValue;
  61192. };
  61193. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  61194. if (newValue !== currentValue) {
  61195. if (newValue === 1) {
  61196. if (this._ondpaddown) {
  61197. this._ondpaddown(buttonType);
  61198. }
  61199. this.onPadDownObservable.notifyObservers(buttonType);
  61200. }
  61201. if (newValue === 0) {
  61202. if (this._ondpadup) {
  61203. this._ondpadup(buttonType);
  61204. }
  61205. this.onPadUpObservable.notifyObservers(buttonType);
  61206. }
  61207. }
  61208. return newValue;
  61209. };
  61210. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  61211. get: function () {
  61212. return this._buttonA;
  61213. },
  61214. set: function (value) {
  61215. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  61216. },
  61217. enumerable: true,
  61218. configurable: true
  61219. });
  61220. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  61221. get: function () {
  61222. return this._buttonB;
  61223. },
  61224. set: function (value) {
  61225. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  61226. },
  61227. enumerable: true,
  61228. configurable: true
  61229. });
  61230. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  61231. get: function () {
  61232. return this._buttonX;
  61233. },
  61234. set: function (value) {
  61235. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  61236. },
  61237. enumerable: true,
  61238. configurable: true
  61239. });
  61240. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  61241. get: function () {
  61242. return this._buttonY;
  61243. },
  61244. set: function (value) {
  61245. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  61246. },
  61247. enumerable: true,
  61248. configurable: true
  61249. });
  61250. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  61251. get: function () {
  61252. return this._buttonStart;
  61253. },
  61254. set: function (value) {
  61255. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  61256. },
  61257. enumerable: true,
  61258. configurable: true
  61259. });
  61260. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  61261. get: function () {
  61262. return this._buttonBack;
  61263. },
  61264. set: function (value) {
  61265. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  61266. },
  61267. enumerable: true,
  61268. configurable: true
  61269. });
  61270. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  61271. get: function () {
  61272. return this._buttonLB;
  61273. },
  61274. set: function (value) {
  61275. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  61276. },
  61277. enumerable: true,
  61278. configurable: true
  61279. });
  61280. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  61281. get: function () {
  61282. return this._buttonRB;
  61283. },
  61284. set: function (value) {
  61285. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  61286. },
  61287. enumerable: true,
  61288. configurable: true
  61289. });
  61290. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  61291. get: function () {
  61292. return this._buttonLeftStick;
  61293. },
  61294. set: function (value) {
  61295. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  61296. },
  61297. enumerable: true,
  61298. configurable: true
  61299. });
  61300. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  61301. get: function () {
  61302. return this._buttonRightStick;
  61303. },
  61304. set: function (value) {
  61305. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  61306. },
  61307. enumerable: true,
  61308. configurable: true
  61309. });
  61310. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  61311. get: function () {
  61312. return this._dPadUp;
  61313. },
  61314. set: function (value) {
  61315. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  61316. },
  61317. enumerable: true,
  61318. configurable: true
  61319. });
  61320. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  61321. get: function () {
  61322. return this._dPadDown;
  61323. },
  61324. set: function (value) {
  61325. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  61326. },
  61327. enumerable: true,
  61328. configurable: true
  61329. });
  61330. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  61331. get: function () {
  61332. return this._dPadLeft;
  61333. },
  61334. set: function (value) {
  61335. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  61336. },
  61337. enumerable: true,
  61338. configurable: true
  61339. });
  61340. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  61341. get: function () {
  61342. return this._dPadRight;
  61343. },
  61344. set: function (value) {
  61345. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  61346. },
  61347. enumerable: true,
  61348. configurable: true
  61349. });
  61350. Xbox360Pad.prototype.update = function () {
  61351. _super.prototype.update.call(this);
  61352. if (this._isXboxOnePad) {
  61353. this.buttonA = this.browserGamepad.buttons[0].value;
  61354. this.buttonB = this.browserGamepad.buttons[1].value;
  61355. this.buttonX = this.browserGamepad.buttons[2].value;
  61356. this.buttonY = this.browserGamepad.buttons[3].value;
  61357. this.buttonLB = this.browserGamepad.buttons[4].value;
  61358. this.buttonRB = this.browserGamepad.buttons[5].value;
  61359. this.leftTrigger = this.browserGamepad.axes[2];
  61360. this.rightTrigger = this.browserGamepad.axes[5];
  61361. this.buttonBack = this.browserGamepad.buttons[9].value;
  61362. this.buttonStart = this.browserGamepad.buttons[8].value;
  61363. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  61364. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  61365. this.dPadUp = this.browserGamepad.buttons[11].value;
  61366. this.dPadDown = this.browserGamepad.buttons[12].value;
  61367. this.dPadLeft = this.browserGamepad.buttons[13].value;
  61368. this.dPadRight = this.browserGamepad.buttons[14].value;
  61369. }
  61370. else {
  61371. this.buttonA = this.browserGamepad.buttons[0].value;
  61372. this.buttonB = this.browserGamepad.buttons[1].value;
  61373. this.buttonX = this.browserGamepad.buttons[2].value;
  61374. this.buttonY = this.browserGamepad.buttons[3].value;
  61375. this.buttonLB = this.browserGamepad.buttons[4].value;
  61376. this.buttonRB = this.browserGamepad.buttons[5].value;
  61377. this.leftTrigger = this.browserGamepad.buttons[6].value;
  61378. this.rightTrigger = this.browserGamepad.buttons[7].value;
  61379. this.buttonBack = this.browserGamepad.buttons[8].value;
  61380. this.buttonStart = this.browserGamepad.buttons[9].value;
  61381. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  61382. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  61383. this.dPadUp = this.browserGamepad.buttons[12].value;
  61384. this.dPadDown = this.browserGamepad.buttons[13].value;
  61385. this.dPadLeft = this.browserGamepad.buttons[14].value;
  61386. this.dPadRight = this.browserGamepad.buttons[15].value;
  61387. }
  61388. };
  61389. Xbox360Pad.prototype.dispose = function () {
  61390. _super.prototype.dispose.call(this);
  61391. this.onButtonDownObservable.clear();
  61392. this.onButtonUpObservable.clear();
  61393. this.onPadDownObservable.clear();
  61394. this.onPadUpObservable.clear();
  61395. };
  61396. return Xbox360Pad;
  61397. }(BABYLON.Gamepad));
  61398. BABYLON.Xbox360Pad = Xbox360Pad;
  61399. })(BABYLON || (BABYLON = {}));
  61400. //# sourceMappingURL=babylon.xboxGamepad.js.map
  61401. var BABYLON;
  61402. (function (BABYLON) {
  61403. var PoseEnabledControllerType;
  61404. (function (PoseEnabledControllerType) {
  61405. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  61406. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  61407. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  61408. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  61409. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  61410. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  61411. var PoseEnabledControllerHelper = /** @class */ (function () {
  61412. function PoseEnabledControllerHelper() {
  61413. }
  61414. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  61415. // Oculus Touch
  61416. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  61417. return new BABYLON.OculusTouchController(vrGamepad);
  61418. }
  61419. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  61420. return new BABYLON.WindowsMotionController(vrGamepad);
  61421. }
  61422. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  61423. return new BABYLON.ViveController(vrGamepad);
  61424. }
  61425. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  61426. return new BABYLON.GearVRController(vrGamepad);
  61427. }
  61428. else {
  61429. return new BABYLON.GenericController(vrGamepad);
  61430. }
  61431. };
  61432. return PoseEnabledControllerHelper;
  61433. }());
  61434. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  61435. var PoseEnabledController = /** @class */ (function (_super) {
  61436. __extends(PoseEnabledController, _super);
  61437. function PoseEnabledController(browserGamepad) {
  61438. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  61439. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  61440. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  61441. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  61442. // Represents device position and rotation in babylon space
  61443. _this.devicePosition = BABYLON.Vector3.Zero();
  61444. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61445. _this.deviceScaleFactor = 1;
  61446. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  61447. _this._deviceToWorld = BABYLON.Matrix.Identity();
  61448. _this._workingMatrix = BABYLON.Matrix.Identity();
  61449. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  61450. _this.controllerType = PoseEnabledControllerType.GENERIC;
  61451. _this.position = BABYLON.Vector3.Zero();
  61452. _this.rotationQuaternion = new BABYLON.Quaternion();
  61453. _this._calculatedPosition = BABYLON.Vector3.Zero();
  61454. _this._calculatedRotation = new BABYLON.Quaternion();
  61455. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  61456. return _this;
  61457. }
  61458. PoseEnabledController.prototype.update = function () {
  61459. _super.prototype.update.call(this);
  61460. var pose = this.browserGamepad.pose;
  61461. this.updateFromDevice(pose);
  61462. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  61463. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  61464. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  61465. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  61466. if (this._mesh) {
  61467. this._mesh.position.copyFrom(this.devicePosition);
  61468. if (this._mesh.rotationQuaternion) {
  61469. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61470. }
  61471. }
  61472. };
  61473. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  61474. if (poseData) {
  61475. this.rawPose = poseData;
  61476. if (poseData.position) {
  61477. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  61478. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  61479. this._deviceRoomPosition.z *= -1;
  61480. }
  61481. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  61482. this._calculatedPosition.addInPlace(this.position);
  61483. }
  61484. var pose = this.rawPose;
  61485. if (poseData.orientation && pose.orientation) {
  61486. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  61487. if (this._mesh) {
  61488. if (this._mesh.getScene().useRightHandedSystem) {
  61489. this._deviceRoomRotationQuaternion.z *= -1;
  61490. this._deviceRoomRotationQuaternion.w *= -1;
  61491. }
  61492. else {
  61493. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  61494. }
  61495. }
  61496. // if the camera is set, rotate to the camera's rotation
  61497. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  61498. }
  61499. }
  61500. };
  61501. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  61502. if (this._mesh) {
  61503. this._mesh.parent = null;
  61504. }
  61505. this._mesh = mesh;
  61506. if (this._poseControlledCamera) {
  61507. this._mesh.parent = this._poseControlledCamera;
  61508. }
  61509. if (!this._mesh.rotationQuaternion) {
  61510. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  61511. }
  61512. };
  61513. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  61514. this._poseControlledCamera = camera;
  61515. if (this._mesh) {
  61516. this._mesh.parent = this._poseControlledCamera;
  61517. }
  61518. };
  61519. PoseEnabledController.prototype.dispose = function () {
  61520. if (this._mesh) {
  61521. this._mesh.dispose();
  61522. }
  61523. this._mesh = null;
  61524. _super.prototype.dispose.call(this);
  61525. };
  61526. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  61527. get: function () {
  61528. return this._mesh;
  61529. },
  61530. enumerable: true,
  61531. configurable: true
  61532. });
  61533. PoseEnabledController.prototype.getForwardRay = function (length) {
  61534. if (length === void 0) { length = 100; }
  61535. if (!this.mesh) {
  61536. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  61537. }
  61538. var m = this.mesh.getWorldMatrix();
  61539. var origin = m.getTranslation();
  61540. var forward = new BABYLON.Vector3(0, 0, -1);
  61541. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61542. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61543. return new BABYLON.Ray(origin, direction, length);
  61544. };
  61545. return PoseEnabledController;
  61546. }(BABYLON.Gamepad));
  61547. BABYLON.PoseEnabledController = PoseEnabledController;
  61548. })(BABYLON || (BABYLON = {}));
  61549. //# sourceMappingURL=babylon.poseEnabledController.js.map
  61550. var BABYLON;
  61551. (function (BABYLON) {
  61552. var WebVRController = /** @class */ (function (_super) {
  61553. __extends(WebVRController, _super);
  61554. function WebVRController(vrGamepad) {
  61555. var _this = _super.call(this, vrGamepad) || this;
  61556. // Observables
  61557. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  61558. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  61559. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  61560. _this.onPadStateChangedObservable = new BABYLON.Observable();
  61561. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  61562. _this.pad = { x: 0, y: 0 };
  61563. // avoid GC, store state in a tmp object
  61564. _this._changes = {
  61565. pressChanged: false,
  61566. touchChanged: false,
  61567. valueChanged: false,
  61568. changed: false
  61569. };
  61570. _this._buttons = new Array(vrGamepad.buttons.length);
  61571. _this.hand = vrGamepad.hand;
  61572. return _this;
  61573. }
  61574. WebVRController.prototype.onButtonStateChange = function (callback) {
  61575. this._onButtonStateChange = callback;
  61576. };
  61577. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  61578. get: function () {
  61579. return this._defaultModel;
  61580. },
  61581. enumerable: true,
  61582. configurable: true
  61583. });
  61584. WebVRController.prototype.update = function () {
  61585. _super.prototype.update.call(this);
  61586. for (var index = 0; index < this._buttons.length; index++) {
  61587. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  61588. }
  61589. ;
  61590. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  61591. this.pad.x = this.leftStick.x;
  61592. this.pad.y = this.leftStick.y;
  61593. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  61594. }
  61595. };
  61596. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  61597. if (!newState) {
  61598. newState = {
  61599. pressed: false,
  61600. touched: false,
  61601. value: 0
  61602. };
  61603. }
  61604. if (!currentState) {
  61605. this._buttons[buttonIndex] = {
  61606. pressed: newState.pressed,
  61607. touched: newState.touched,
  61608. value: newState.value
  61609. };
  61610. return;
  61611. }
  61612. this._checkChanges(newState, currentState);
  61613. if (this._changes.changed) {
  61614. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  61615. this.handleButtonChange(buttonIndex, newState, this._changes);
  61616. }
  61617. this._buttons[buttonIndex].pressed = newState.pressed;
  61618. this._buttons[buttonIndex].touched = newState.touched;
  61619. // oculus triggers are never 0, thou not touched.
  61620. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  61621. };
  61622. WebVRController.prototype._checkChanges = function (newState, currentState) {
  61623. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  61624. this._changes.touchChanged = newState.touched !== currentState.touched;
  61625. this._changes.valueChanged = newState.value !== currentState.value;
  61626. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  61627. return this._changes;
  61628. };
  61629. WebVRController.prototype.dispose = function () {
  61630. _super.prototype.dispose.call(this);
  61631. this.onTriggerStateChangedObservable.clear();
  61632. this.onMainButtonStateChangedObservable.clear();
  61633. this.onSecondaryButtonStateChangedObservable.clear();
  61634. this.onPadStateChangedObservable.clear();
  61635. this.onPadValuesChangedObservable.clear();
  61636. };
  61637. return WebVRController;
  61638. }(BABYLON.PoseEnabledController));
  61639. BABYLON.WebVRController = WebVRController;
  61640. })(BABYLON || (BABYLON = {}));
  61641. //# sourceMappingURL=babylon.webVRController.js.map
  61642. var BABYLON;
  61643. (function (BABYLON) {
  61644. var OculusTouchController = /** @class */ (function (_super) {
  61645. __extends(OculusTouchController, _super);
  61646. function OculusTouchController(vrGamepad) {
  61647. var _this = _super.call(this, vrGamepad) || this;
  61648. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  61649. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  61650. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  61651. return _this;
  61652. }
  61653. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61654. var _this = this;
  61655. var meshName;
  61656. // Hand
  61657. if (this.hand === 'left') {
  61658. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  61659. }
  61660. else {
  61661. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  61662. }
  61663. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  61664. /*
  61665. Parent Mesh name: oculus_touch_left
  61666. - body
  61667. - trigger
  61668. - thumbstick
  61669. - grip
  61670. - button_y
  61671. - button_x
  61672. - button_enter
  61673. */
  61674. _this._defaultModel = newMeshes[1];
  61675. _this.attachToMesh(_this._defaultModel);
  61676. if (meshLoaded) {
  61677. meshLoaded(_this._defaultModel);
  61678. }
  61679. });
  61680. };
  61681. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  61682. // helper getters for left and right hand.
  61683. get: function () {
  61684. if (this.hand === 'right') {
  61685. return this.onMainButtonStateChangedObservable;
  61686. }
  61687. else {
  61688. throw new Error('No A button on left hand');
  61689. }
  61690. },
  61691. enumerable: true,
  61692. configurable: true
  61693. });
  61694. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  61695. get: function () {
  61696. if (this.hand === 'right') {
  61697. return this.onSecondaryButtonStateChangedObservable;
  61698. }
  61699. else {
  61700. throw new Error('No B button on left hand');
  61701. }
  61702. },
  61703. enumerable: true,
  61704. configurable: true
  61705. });
  61706. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  61707. get: function () {
  61708. if (this.hand === 'left') {
  61709. return this.onMainButtonStateChangedObservable;
  61710. }
  61711. else {
  61712. throw new Error('No X button on right hand');
  61713. }
  61714. },
  61715. enumerable: true,
  61716. configurable: true
  61717. });
  61718. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  61719. get: function () {
  61720. if (this.hand === 'left') {
  61721. return this.onSecondaryButtonStateChangedObservable;
  61722. }
  61723. else {
  61724. throw new Error('No Y button on right hand');
  61725. }
  61726. },
  61727. enumerable: true,
  61728. configurable: true
  61729. });
  61730. /*
  61731. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  61732. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  61733. 2) secondary trigger (same)
  61734. 3) A (right) X (left), touch, pressed = value
  61735. 4) B / Y
  61736. 5) thumb rest
  61737. */
  61738. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61739. var notifyObject = state; //{ state: state, changes: changes };
  61740. var triggerDirection = this.hand === 'right' ? -1 : 1;
  61741. switch (buttonIdx) {
  61742. case 0:
  61743. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61744. return;
  61745. case 1:// index trigger
  61746. if (this._defaultModel) {
  61747. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  61748. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  61749. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  61750. }
  61751. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61752. return;
  61753. case 2:// secondary trigger
  61754. if (this._defaultModel) {
  61755. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  61756. }
  61757. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  61758. return;
  61759. case 3:
  61760. if (this._defaultModel) {
  61761. if (notifyObject.pressed) {
  61762. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  61763. }
  61764. else {
  61765. (this._defaultModel.getChildren()[1]).position.y = 0;
  61766. }
  61767. }
  61768. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61769. return;
  61770. case 4:
  61771. if (this._defaultModel) {
  61772. if (notifyObject.pressed) {
  61773. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61774. }
  61775. else {
  61776. (this._defaultModel.getChildren()[2]).position.y = 0;
  61777. }
  61778. }
  61779. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61780. return;
  61781. case 5:
  61782. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  61783. return;
  61784. }
  61785. };
  61786. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  61787. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  61788. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  61789. return OculusTouchController;
  61790. }(BABYLON.WebVRController));
  61791. BABYLON.OculusTouchController = OculusTouchController;
  61792. })(BABYLON || (BABYLON = {}));
  61793. //# sourceMappingURL=babylon.oculusTouchController.js.map
  61794. var BABYLON;
  61795. (function (BABYLON) {
  61796. var ViveController = /** @class */ (function (_super) {
  61797. __extends(ViveController, _super);
  61798. function ViveController(vrGamepad) {
  61799. var _this = _super.call(this, vrGamepad) || this;
  61800. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  61801. _this._invertLeftStickY = true;
  61802. return _this;
  61803. }
  61804. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61805. var _this = this;
  61806. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  61807. /*
  61808. Parent Mesh name: ViveWand
  61809. - body
  61810. - r_gripper
  61811. - l_gripper
  61812. - menu_button
  61813. - system_button
  61814. - trackpad
  61815. - trigger
  61816. - LED
  61817. */
  61818. _this._defaultModel = newMeshes[1];
  61819. _this.attachToMesh(_this._defaultModel);
  61820. if (meshLoaded) {
  61821. meshLoaded(_this._defaultModel);
  61822. }
  61823. });
  61824. };
  61825. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  61826. get: function () {
  61827. return this.onMainButtonStateChangedObservable;
  61828. },
  61829. enumerable: true,
  61830. configurable: true
  61831. });
  61832. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  61833. get: function () {
  61834. return this.onMainButtonStateChangedObservable;
  61835. },
  61836. enumerable: true,
  61837. configurable: true
  61838. });
  61839. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  61840. get: function () {
  61841. return this.onSecondaryButtonStateChangedObservable;
  61842. },
  61843. enumerable: true,
  61844. configurable: true
  61845. });
  61846. /**
  61847. * Vive mapping:
  61848. * 0: touchpad
  61849. * 1: trigger
  61850. * 2: left AND right buttons
  61851. * 3: menu button
  61852. */
  61853. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61854. var notifyObject = state; //{ state: state, changes: changes };
  61855. switch (buttonIdx) {
  61856. case 0:
  61857. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61858. return;
  61859. case 1:// index trigger
  61860. if (this._defaultModel) {
  61861. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  61862. }
  61863. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61864. return;
  61865. case 2:// left AND right button
  61866. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61867. return;
  61868. case 3:
  61869. if (this._defaultModel) {
  61870. if (notifyObject.pressed) {
  61871. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61872. }
  61873. else {
  61874. (this._defaultModel.getChildren()[2]).position.y = 0;
  61875. }
  61876. }
  61877. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61878. return;
  61879. }
  61880. };
  61881. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  61882. ViveController.MODEL_FILENAME = 'wand.babylon';
  61883. return ViveController;
  61884. }(BABYLON.WebVRController));
  61885. BABYLON.ViveController = ViveController;
  61886. })(BABYLON || (BABYLON = {}));
  61887. //# sourceMappingURL=babylon.viveController.js.map
  61888. var BABYLON;
  61889. (function (BABYLON) {
  61890. var GenericController = /** @class */ (function (_super) {
  61891. __extends(GenericController, _super);
  61892. function GenericController(vrGamepad) {
  61893. return _super.call(this, vrGamepad) || this;
  61894. }
  61895. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61896. var _this = this;
  61897. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  61898. _this._defaultModel = newMeshes[1];
  61899. _this.attachToMesh(_this._defaultModel);
  61900. if (meshLoaded) {
  61901. meshLoaded(_this._defaultModel);
  61902. }
  61903. });
  61904. };
  61905. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61906. console.log("Button id: " + buttonIdx + "state: ");
  61907. console.dir(state);
  61908. };
  61909. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61910. GenericController.MODEL_FILENAME = 'generic.babylon';
  61911. return GenericController;
  61912. }(BABYLON.WebVRController));
  61913. BABYLON.GenericController = GenericController;
  61914. })(BABYLON || (BABYLON = {}));
  61915. //# sourceMappingURL=babylon.genericController.js.map
  61916. var BABYLON;
  61917. (function (BABYLON) {
  61918. var LoadedMeshInfo = /** @class */ (function () {
  61919. function LoadedMeshInfo() {
  61920. this.buttonMeshes = {};
  61921. this.axisMeshes = {};
  61922. }
  61923. return LoadedMeshInfo;
  61924. }());
  61925. var WindowsMotionController = /** @class */ (function (_super) {
  61926. __extends(WindowsMotionController, _super);
  61927. function WindowsMotionController(vrGamepad) {
  61928. var _this = _super.call(this, vrGamepad) || this;
  61929. _this._mapping = {
  61930. // Semantic button names
  61931. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  61932. // A mapping of the button name to glTF model node name
  61933. // that should be transformed by button value.
  61934. buttonMeshNames: {
  61935. 'trigger': 'SELECT',
  61936. 'menu': 'MENU',
  61937. 'grip': 'GRASP',
  61938. 'thumbstick': 'THUMBSTICK_PRESS',
  61939. 'trackpad': 'TOUCHPAD_PRESS'
  61940. },
  61941. // This mapping is used to translate from the Motion Controller to Babylon semantics
  61942. buttonObservableNames: {
  61943. 'trigger': 'onTriggerStateChangedObservable',
  61944. 'menu': 'onSecondaryButtonStateChangedObservable',
  61945. 'grip': 'onMainButtonStateChangedObservable',
  61946. 'thumbstick': 'onPadStateChangedObservable',
  61947. 'trackpad': 'onTrackpadChangedObservable'
  61948. },
  61949. // A mapping of the axis name to glTF model node name
  61950. // that should be transformed by axis value.
  61951. // This array mirrors the browserGamepad.axes array, such that
  61952. // the mesh corresponding to axis 0 is in this array index 0.
  61953. axisMeshNames: [
  61954. 'THUMBSTICK_X',
  61955. 'THUMBSTICK_Y',
  61956. 'TOUCHPAD_TOUCH_X',
  61957. 'TOUCHPAD_TOUCH_Y'
  61958. ],
  61959. pointingPoseMeshName: 'POINTING_POSE'
  61960. };
  61961. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  61962. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  61963. _this.trackpad = { x: 0, y: 0 };
  61964. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  61965. _this._loadedMeshInfo = null;
  61966. return _this;
  61967. }
  61968. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  61969. get: function () {
  61970. return this.onTriggerStateChangedObservable;
  61971. },
  61972. enumerable: true,
  61973. configurable: true
  61974. });
  61975. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  61976. get: function () {
  61977. return this.onSecondaryButtonStateChangedObservable;
  61978. },
  61979. enumerable: true,
  61980. configurable: true
  61981. });
  61982. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  61983. get: function () {
  61984. return this.onMainButtonStateChangedObservable;
  61985. },
  61986. enumerable: true,
  61987. configurable: true
  61988. });
  61989. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  61990. get: function () {
  61991. return this.onPadStateChangedObservable;
  61992. },
  61993. enumerable: true,
  61994. configurable: true
  61995. });
  61996. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  61997. get: function () {
  61998. return this.onTrackpadChangedObservable;
  61999. },
  62000. enumerable: true,
  62001. configurable: true
  62002. });
  62003. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  62004. get: function () {
  62005. return this.onTrackpadValuesChangedObservable;
  62006. },
  62007. enumerable: true,
  62008. configurable: true
  62009. });
  62010. /**
  62011. * Called once per frame by the engine.
  62012. */
  62013. WindowsMotionController.prototype.update = function () {
  62014. _super.prototype.update.call(this);
  62015. // Only need to animate axes if there is a loaded mesh
  62016. if (this._loadedMeshInfo) {
  62017. if (this.browserGamepad.axes) {
  62018. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  62019. this.trackpad.x = this.browserGamepad["axes"][2];
  62020. this.trackpad.y = this.browserGamepad["axes"][3];
  62021. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  62022. }
  62023. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  62024. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  62025. }
  62026. }
  62027. }
  62028. };
  62029. /**
  62030. * Called once for each button that changed state since the last frame
  62031. * @param buttonIdx Which button index changed
  62032. * @param state New state of the button
  62033. * @param changes Which properties on the state changed since last frame
  62034. */
  62035. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62036. var buttonName = this._mapping.buttons[buttonIdx];
  62037. if (!buttonName) {
  62038. return;
  62039. }
  62040. // Only emit events for buttons that we know how to map from index to name
  62041. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  62042. if (observable) {
  62043. observable.notifyObservers(state);
  62044. }
  62045. this.lerpButtonTransform(buttonName, state.value);
  62046. };
  62047. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  62048. // If there is no loaded mesh, there is nothing to transform.
  62049. if (!this._loadedMeshInfo) {
  62050. return;
  62051. }
  62052. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  62053. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  62054. return;
  62055. }
  62056. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  62057. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  62058. };
  62059. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  62060. if (!this._loadedMeshInfo) {
  62061. return;
  62062. }
  62063. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  62064. if (!meshInfo) {
  62065. return;
  62066. }
  62067. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  62068. return;
  62069. }
  62070. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  62071. var lerpValue = axisValue * 0.5 + 0.5;
  62072. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  62073. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  62074. };
  62075. /**
  62076. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  62077. * @param scene scene in which to add meshes
  62078. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  62079. */
  62080. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  62081. var _this = this;
  62082. if (forceDefault === void 0) { forceDefault = false; }
  62083. var path;
  62084. var filename;
  62085. // Checking if GLB loader is present
  62086. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  62087. // Determine the device specific folder based on the ID suffix
  62088. var device = 'default';
  62089. if (this.id && !forceDefault) {
  62090. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  62091. device = ((match && match[0]) || device);
  62092. }
  62093. // Hand
  62094. if (this.hand === 'left') {
  62095. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  62096. }
  62097. else {
  62098. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  62099. }
  62100. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  62101. }
  62102. else {
  62103. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  62104. path = BABYLON.GenericController.MODEL_BASE_URL;
  62105. filename = BABYLON.GenericController.MODEL_FILENAME;
  62106. }
  62107. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  62108. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  62109. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  62110. if (!_this._loadedMeshInfo) {
  62111. return;
  62112. }
  62113. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  62114. _this.attachToMesh(_this._defaultModel);
  62115. if (meshLoaded) {
  62116. meshLoaded(_this._defaultModel);
  62117. }
  62118. }, null, function (scene, message) {
  62119. BABYLON.Tools.Log(message);
  62120. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  62121. if (!forceDefault) {
  62122. _this.initControllerMesh(scene, meshLoaded, true);
  62123. }
  62124. });
  62125. };
  62126. /**
  62127. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  62128. * can be transformed by button presses and axes values, based on this._mapping.
  62129. *
  62130. * @param scene scene in which the meshes exist
  62131. * @param meshes list of meshes that make up the controller model to process
  62132. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  62133. */
  62134. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  62135. var loadedMeshInfo = null;
  62136. // Create a new mesh to contain the glTF hierarchy
  62137. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  62138. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  62139. var childMesh = null;
  62140. for (var i = 0; i < meshes.length; i++) {
  62141. var mesh = meshes[i];
  62142. if (!mesh.parent) {
  62143. // Exclude controller meshes from picking results
  62144. mesh.isPickable = false;
  62145. // Handle root node, attach to the new parentMesh
  62146. childMesh = mesh;
  62147. break;
  62148. }
  62149. }
  62150. if (childMesh) {
  62151. childMesh.setParent(parentMesh);
  62152. // Create our mesh info. Note that this method will always return non-null.
  62153. loadedMeshInfo = this.createMeshInfo(parentMesh);
  62154. }
  62155. else {
  62156. BABYLON.Tools.Warn('Could not find root node in model file.');
  62157. }
  62158. return loadedMeshInfo;
  62159. };
  62160. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  62161. var loadedMeshInfo = new LoadedMeshInfo();
  62162. var i;
  62163. loadedMeshInfo.rootNode = rootNode;
  62164. // Reset the caches
  62165. loadedMeshInfo.buttonMeshes = {};
  62166. loadedMeshInfo.axisMeshes = {};
  62167. // Button Meshes
  62168. for (i = 0; i < this._mapping.buttons.length; i++) {
  62169. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  62170. if (!buttonMeshName) {
  62171. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  62172. continue;
  62173. }
  62174. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  62175. if (!buttonMesh) {
  62176. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  62177. continue;
  62178. }
  62179. var buttonMeshInfo = {
  62180. index: i,
  62181. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  62182. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  62183. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  62184. };
  62185. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  62186. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  62187. }
  62188. else {
  62189. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  62190. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  62191. '(VALUE: ' + !!buttonMeshInfo.value +
  62192. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  62193. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  62194. ')');
  62195. }
  62196. }
  62197. // Axis Meshes
  62198. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  62199. var axisMeshName = this._mapping.axisMeshNames[i];
  62200. if (!axisMeshName) {
  62201. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  62202. continue;
  62203. }
  62204. var axisMesh = getChildByName(rootNode, axisMeshName);
  62205. if (!axisMesh) {
  62206. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  62207. continue;
  62208. }
  62209. var axisMeshInfo = {
  62210. index: i,
  62211. value: getImmediateChildByName(axisMesh, 'VALUE'),
  62212. min: getImmediateChildByName(axisMesh, 'MIN'),
  62213. max: getImmediateChildByName(axisMesh, 'MAX')
  62214. };
  62215. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  62216. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  62217. }
  62218. else {
  62219. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  62220. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  62221. '(VALUE: ' + !!axisMeshInfo.value +
  62222. ', MIN: ' + !!axisMeshInfo.min +
  62223. ', MAX:' + !!axisMeshInfo.max +
  62224. ')');
  62225. }
  62226. }
  62227. // Pointing Ray
  62228. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  62229. if (!loadedMeshInfo.pointingPoseNode) {
  62230. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  62231. }
  62232. return loadedMeshInfo;
  62233. // Look through all children recursively. This will return null if no mesh exists with the given name.
  62234. function getChildByName(node, name) {
  62235. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  62236. }
  62237. // Look through only immediate children. This will return null if no mesh exists with the given name.
  62238. function getImmediateChildByName(node, name) {
  62239. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  62240. }
  62241. };
  62242. WindowsMotionController.prototype.getForwardRay = function (length) {
  62243. if (length === void 0) { length = 100; }
  62244. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  62245. return _super.prototype.getForwardRay.call(this, length);
  62246. }
  62247. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  62248. var origin = m.getTranslation();
  62249. var forward = new BABYLON.Vector3(0, 0, -1);
  62250. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  62251. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  62252. return new BABYLON.Ray(origin, direction, length);
  62253. };
  62254. WindowsMotionController.prototype.dispose = function () {
  62255. _super.prototype.dispose.call(this);
  62256. this.onTrackpadChangedObservable.clear();
  62257. };
  62258. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  62259. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  62260. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  62261. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  62262. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  62263. return WindowsMotionController;
  62264. }(BABYLON.WebVRController));
  62265. BABYLON.WindowsMotionController = WindowsMotionController;
  62266. })(BABYLON || (BABYLON = {}));
  62267. //# sourceMappingURL=babylon.windowsMotionController.js.map
  62268. var BABYLON;
  62269. (function (BABYLON) {
  62270. var GearVRController = /** @class */ (function (_super) {
  62271. __extends(GearVRController, _super);
  62272. function GearVRController(vrGamepad) {
  62273. var _this = _super.call(this, vrGamepad) || this;
  62274. _this._buttonIndexToObservableNameMap = [
  62275. 'onTrackpadChangedObservable',
  62276. 'onTriggerStateChangedObservable' // Trigger
  62277. ];
  62278. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  62279. return _this;
  62280. }
  62281. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62282. var _this = this;
  62283. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  62284. _this._defaultModel = newMeshes[1];
  62285. _this.attachToMesh(_this._defaultModel);
  62286. if (meshLoaded) {
  62287. meshLoaded(_this._defaultModel);
  62288. }
  62289. });
  62290. };
  62291. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62292. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  62293. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  62294. // Only emit events for buttons that we know how to map from index to observable
  62295. var observable = this[observableName];
  62296. if (observable) {
  62297. observable.notifyObservers(state);
  62298. }
  62299. }
  62300. };
  62301. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  62302. GearVRController.MODEL_FILENAME = 'generic.babylon';
  62303. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  62304. return GearVRController;
  62305. }(BABYLON.WebVRController));
  62306. BABYLON.GearVRController = GearVRController;
  62307. })(BABYLON || (BABYLON = {}));
  62308. //# sourceMappingURL=babylon.gearVRController.js.map
  62309. var BABYLON;
  62310. (function (BABYLON) {
  62311. var FollowCamera = /** @class */ (function (_super) {
  62312. __extends(FollowCamera, _super);
  62313. function FollowCamera(name, position, scene, lockedTarget) {
  62314. if (lockedTarget === void 0) { lockedTarget = null; }
  62315. var _this = _super.call(this, name, position, scene) || this;
  62316. _this.radius = 12;
  62317. _this.rotationOffset = 0;
  62318. _this.heightOffset = 4;
  62319. _this.cameraAcceleration = 0.05;
  62320. _this.maxCameraSpeed = 20;
  62321. _this.lockedTarget = lockedTarget;
  62322. return _this;
  62323. }
  62324. FollowCamera.prototype.getRadians = function (degrees) {
  62325. return degrees * Math.PI / 180;
  62326. };
  62327. FollowCamera.prototype.follow = function (cameraTarget) {
  62328. if (!cameraTarget)
  62329. return;
  62330. var yRotation;
  62331. if (cameraTarget.rotationQuaternion) {
  62332. var rotMatrix = new BABYLON.Matrix();
  62333. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  62334. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  62335. }
  62336. else {
  62337. yRotation = cameraTarget.rotation.y;
  62338. }
  62339. var radians = this.getRadians(this.rotationOffset) + yRotation;
  62340. var targetPosition = cameraTarget.getAbsolutePosition();
  62341. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  62342. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  62343. var dx = targetX - this.position.x;
  62344. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  62345. var dz = (targetZ) - this.position.z;
  62346. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  62347. var vy = dy * this.cameraAcceleration;
  62348. var vz = dz * this.cameraAcceleration * 2;
  62349. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  62350. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62351. }
  62352. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  62353. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62354. }
  62355. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  62356. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62357. }
  62358. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  62359. this.setTarget(targetPosition);
  62360. };
  62361. FollowCamera.prototype._checkInputs = function () {
  62362. _super.prototype._checkInputs.call(this);
  62363. if (this.lockedTarget) {
  62364. this.follow(this.lockedTarget);
  62365. }
  62366. };
  62367. FollowCamera.prototype.getClassName = function () {
  62368. return "FollowCamera";
  62369. };
  62370. __decorate([
  62371. BABYLON.serialize()
  62372. ], FollowCamera.prototype, "radius", void 0);
  62373. __decorate([
  62374. BABYLON.serialize()
  62375. ], FollowCamera.prototype, "rotationOffset", void 0);
  62376. __decorate([
  62377. BABYLON.serialize()
  62378. ], FollowCamera.prototype, "heightOffset", void 0);
  62379. __decorate([
  62380. BABYLON.serialize()
  62381. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  62382. __decorate([
  62383. BABYLON.serialize()
  62384. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  62385. __decorate([
  62386. BABYLON.serializeAsMeshReference("lockedTargetId")
  62387. ], FollowCamera.prototype, "lockedTarget", void 0);
  62388. return FollowCamera;
  62389. }(BABYLON.TargetCamera));
  62390. BABYLON.FollowCamera = FollowCamera;
  62391. var ArcFollowCamera = /** @class */ (function (_super) {
  62392. __extends(ArcFollowCamera, _super);
  62393. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  62394. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  62395. _this.alpha = alpha;
  62396. _this.beta = beta;
  62397. _this.radius = radius;
  62398. _this.target = target;
  62399. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  62400. _this.follow();
  62401. return _this;
  62402. }
  62403. ArcFollowCamera.prototype.follow = function () {
  62404. if (!this.target) {
  62405. return;
  62406. }
  62407. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  62408. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  62409. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  62410. var targetPosition = this.target.getAbsolutePosition();
  62411. this.position = targetPosition.add(this._cartesianCoordinates);
  62412. this.setTarget(targetPosition);
  62413. };
  62414. ArcFollowCamera.prototype._checkInputs = function () {
  62415. _super.prototype._checkInputs.call(this);
  62416. this.follow();
  62417. };
  62418. ArcFollowCamera.prototype.getClassName = function () {
  62419. return "ArcFollowCamera";
  62420. };
  62421. return ArcFollowCamera;
  62422. }(BABYLON.TargetCamera));
  62423. BABYLON.ArcFollowCamera = ArcFollowCamera;
  62424. })(BABYLON || (BABYLON = {}));
  62425. //# sourceMappingURL=babylon.followCamera.js.map
  62426. var BABYLON;
  62427. (function (BABYLON) {
  62428. // We're mainly based on the logic defined into the FreeCamera code
  62429. var UniversalCamera = /** @class */ (function (_super) {
  62430. __extends(UniversalCamera, _super);
  62431. //-- end properties for backward compatibility for inputs
  62432. function UniversalCamera(name, position, scene) {
  62433. var _this = _super.call(this, name, position, scene) || this;
  62434. _this.inputs.addGamepad();
  62435. return _this;
  62436. }
  62437. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  62438. //-- Begin properties for backward compatibility for inputs
  62439. get: function () {
  62440. var gamepad = this.inputs.attached["gamepad"];
  62441. if (gamepad)
  62442. return gamepad.gamepadAngularSensibility;
  62443. return 0;
  62444. },
  62445. set: function (value) {
  62446. var gamepad = this.inputs.attached["gamepad"];
  62447. if (gamepad)
  62448. gamepad.gamepadAngularSensibility = value;
  62449. },
  62450. enumerable: true,
  62451. configurable: true
  62452. });
  62453. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  62454. get: function () {
  62455. var gamepad = this.inputs.attached["gamepad"];
  62456. if (gamepad)
  62457. return gamepad.gamepadMoveSensibility;
  62458. return 0;
  62459. },
  62460. set: function (value) {
  62461. var gamepad = this.inputs.attached["gamepad"];
  62462. if (gamepad)
  62463. gamepad.gamepadMoveSensibility = value;
  62464. },
  62465. enumerable: true,
  62466. configurable: true
  62467. });
  62468. UniversalCamera.prototype.getClassName = function () {
  62469. return "UniversalCamera";
  62470. };
  62471. return UniversalCamera;
  62472. }(BABYLON.TouchCamera));
  62473. BABYLON.UniversalCamera = UniversalCamera;
  62474. })(BABYLON || (BABYLON = {}));
  62475. //# sourceMappingURL=babylon.universalCamera.js.map
  62476. var BABYLON;
  62477. (function (BABYLON) {
  62478. // We're mainly based on the logic defined into the FreeCamera code
  62479. var GamepadCamera = /** @class */ (function (_super) {
  62480. __extends(GamepadCamera, _super);
  62481. //-- end properties for backward compatibility for inputs
  62482. function GamepadCamera(name, position, scene) {
  62483. return _super.call(this, name, position, scene) || this;
  62484. }
  62485. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  62486. //-- Begin properties for backward compatibility for inputs
  62487. get: function () {
  62488. var gamepad = this.inputs.attached["gamepad"];
  62489. if (gamepad)
  62490. return gamepad.gamepadAngularSensibility;
  62491. return 0;
  62492. },
  62493. set: function (value) {
  62494. var gamepad = this.inputs.attached["gamepad"];
  62495. if (gamepad)
  62496. gamepad.gamepadAngularSensibility = value;
  62497. },
  62498. enumerable: true,
  62499. configurable: true
  62500. });
  62501. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  62502. get: function () {
  62503. var gamepad = this.inputs.attached["gamepad"];
  62504. if (gamepad)
  62505. return gamepad.gamepadMoveSensibility;
  62506. return 0;
  62507. },
  62508. set: function (value) {
  62509. var gamepad = this.inputs.attached["gamepad"];
  62510. if (gamepad)
  62511. gamepad.gamepadMoveSensibility = value;
  62512. },
  62513. enumerable: true,
  62514. configurable: true
  62515. });
  62516. GamepadCamera.prototype.getClassName = function () {
  62517. return "GamepadCamera";
  62518. };
  62519. return GamepadCamera;
  62520. }(BABYLON.UniversalCamera));
  62521. BABYLON.GamepadCamera = GamepadCamera;
  62522. })(BABYLON || (BABYLON = {}));
  62523. //# sourceMappingURL=babylon.gamepadCamera.js.map
  62524. var BABYLON;
  62525. (function (BABYLON) {
  62526. var PostProcessRenderPipelineManager = /** @class */ (function () {
  62527. function PostProcessRenderPipelineManager() {
  62528. this._renderPipelines = {};
  62529. }
  62530. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  62531. this._renderPipelines[renderPipeline._name] = renderPipeline;
  62532. };
  62533. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  62534. if (unique === void 0) { unique = false; }
  62535. var renderPipeline = this._renderPipelines[renderPipelineName];
  62536. if (!renderPipeline) {
  62537. return;
  62538. }
  62539. renderPipeline._attachCameras(cameras, unique);
  62540. };
  62541. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  62542. var renderPipeline = this._renderPipelines[renderPipelineName];
  62543. if (!renderPipeline) {
  62544. return;
  62545. }
  62546. renderPipeline._detachCameras(cameras);
  62547. };
  62548. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62549. var renderPipeline = this._renderPipelines[renderPipelineName];
  62550. if (!renderPipeline) {
  62551. return;
  62552. }
  62553. renderPipeline._enableEffect(renderEffectName, cameras);
  62554. };
  62555. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62556. var renderPipeline = this._renderPipelines[renderPipelineName];
  62557. if (!renderPipeline) {
  62558. return;
  62559. }
  62560. renderPipeline._disableEffect(renderEffectName, cameras);
  62561. };
  62562. PostProcessRenderPipelineManager.prototype.update = function () {
  62563. for (var renderPipelineName in this._renderPipelines) {
  62564. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62565. var pipeline = this._renderPipelines[renderPipelineName];
  62566. if (!pipeline.isSupported) {
  62567. pipeline.dispose();
  62568. delete this._renderPipelines[renderPipelineName];
  62569. }
  62570. else {
  62571. pipeline._update();
  62572. }
  62573. }
  62574. }
  62575. };
  62576. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  62577. for (var renderPipelineName in this._renderPipelines) {
  62578. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62579. var pipeline = this._renderPipelines[renderPipelineName];
  62580. pipeline._rebuild();
  62581. }
  62582. }
  62583. };
  62584. PostProcessRenderPipelineManager.prototype.dispose = function () {
  62585. for (var renderPipelineName in this._renderPipelines) {
  62586. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62587. var pipeline = this._renderPipelines[renderPipelineName];
  62588. pipeline.dispose();
  62589. }
  62590. }
  62591. };
  62592. return PostProcessRenderPipelineManager;
  62593. }());
  62594. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  62595. })(BABYLON || (BABYLON = {}));
  62596. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  62597. var BABYLON;
  62598. (function (BABYLON) {
  62599. /**
  62600. * This represents a set of one or more post processes in Babylon.
  62601. * A post process can be used to apply a shader to a texture after it is rendered.
  62602. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  62603. */
  62604. var PostProcessRenderEffect = /** @class */ (function () {
  62605. /**
  62606. * Instantiates a post process render effect.
  62607. * A post process can be used to apply a shader to a texture after it is rendered.
  62608. * @param engine The engine the effect is tied to
  62609. * @param name The name of the effect
  62610. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  62611. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  62612. */
  62613. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  62614. this._name = name;
  62615. this._singleInstance = singleInstance || true;
  62616. this._getPostProcesses = getPostProcesses;
  62617. this._cameras = {};
  62618. this._indicesForCamera = {};
  62619. this._postProcesses = {};
  62620. }
  62621. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  62622. /**
  62623. * Checks if all the post processes in the effect are supported.
  62624. */
  62625. get: function () {
  62626. for (var index in this._postProcesses) {
  62627. for (var ppIndex in this._postProcesses[index]) {
  62628. if (!this._postProcesses[index][ppIndex].isSupported) {
  62629. return false;
  62630. }
  62631. }
  62632. }
  62633. return true;
  62634. },
  62635. enumerable: true,
  62636. configurable: true
  62637. });
  62638. /**
  62639. * Updates the current state of the effect
  62640. */
  62641. PostProcessRenderEffect.prototype._update = function () {
  62642. };
  62643. /**
  62644. * Attaches the effect on cameras
  62645. * @param cameras The camera to attach to.
  62646. */
  62647. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  62648. var _this = this;
  62649. var cameraKey;
  62650. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62651. if (!cams) {
  62652. return;
  62653. }
  62654. for (var i = 0; i < cams.length; i++) {
  62655. var camera = cams[i];
  62656. var cameraName = camera.name;
  62657. if (this._singleInstance) {
  62658. cameraKey = 0;
  62659. }
  62660. else {
  62661. cameraKey = cameraName;
  62662. }
  62663. if (!this._postProcesses[cameraKey]) {
  62664. var postProcess = this._getPostProcesses();
  62665. if (postProcess) {
  62666. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  62667. }
  62668. }
  62669. if (!this._indicesForCamera[cameraName]) {
  62670. this._indicesForCamera[cameraName] = [];
  62671. }
  62672. this._postProcesses[cameraKey].forEach(function (postProcess) {
  62673. var index = camera.attachPostProcess(postProcess);
  62674. _this._indicesForCamera[cameraName].push(index);
  62675. });
  62676. if (!this._cameras[cameraName]) {
  62677. this._cameras[cameraName] = camera;
  62678. }
  62679. }
  62680. };
  62681. /**
  62682. * Detatches the effect on cameras
  62683. * @param cameras The camera to detatch from.
  62684. */
  62685. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  62686. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62687. if (!cams) {
  62688. return;
  62689. }
  62690. for (var i = 0; i < cams.length; i++) {
  62691. var camera = cams[i];
  62692. var cameraName = camera.name;
  62693. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  62694. camera.detachPostProcess(postProcess);
  62695. });
  62696. if (this._cameras[cameraName]) {
  62697. //this._indicesForCamera.splice(index, 1);
  62698. this._cameras[cameraName] = null;
  62699. }
  62700. }
  62701. };
  62702. /**
  62703. * Enables the effect on given cameras
  62704. * @param cameras The camera to enable.
  62705. */
  62706. PostProcessRenderEffect.prototype._enable = function (cameras) {
  62707. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62708. if (!cams) {
  62709. return;
  62710. }
  62711. for (var i = 0; i < cams.length; i++) {
  62712. var camera = cams[i];
  62713. var cameraName = camera.name;
  62714. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  62715. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  62716. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  62717. }
  62718. }
  62719. }
  62720. };
  62721. /**
  62722. * Disables the effect on the given cameras
  62723. * @param cameras The camera to disable.
  62724. */
  62725. PostProcessRenderEffect.prototype._disable = function (cameras) {
  62726. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62727. if (!cams) {
  62728. return;
  62729. }
  62730. for (var i = 0; i < cams.length; i++) {
  62731. var camera = cams[i];
  62732. var cameraName = camera.Name;
  62733. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  62734. }
  62735. };
  62736. /**
  62737. * Gets a list of the post processes contained in the effect.
  62738. * @param camera The camera to get the post processes on.
  62739. * @returns The list of the post processes in the effect.
  62740. */
  62741. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  62742. if (this._singleInstance) {
  62743. return this._postProcesses[0];
  62744. }
  62745. else {
  62746. if (!camera) {
  62747. return null;
  62748. }
  62749. return this._postProcesses[camera.name];
  62750. }
  62751. };
  62752. return PostProcessRenderEffect;
  62753. }());
  62754. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  62755. })(BABYLON || (BABYLON = {}));
  62756. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  62757. var BABYLON;
  62758. (function (BABYLON) {
  62759. var PostProcessRenderPipeline = /** @class */ (function () {
  62760. function PostProcessRenderPipeline(engine, name) {
  62761. this._name = name;
  62762. this._renderEffects = {};
  62763. this._renderEffectsForIsolatedPass = new Array();
  62764. this._cameras = [];
  62765. }
  62766. PostProcessRenderPipeline.prototype.getClassName = function () {
  62767. return "PostProcessRenderPipeline";
  62768. };
  62769. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  62770. get: function () {
  62771. for (var renderEffectName in this._renderEffects) {
  62772. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62773. if (!this._renderEffects[renderEffectName].isSupported) {
  62774. return false;
  62775. }
  62776. }
  62777. }
  62778. return true;
  62779. },
  62780. enumerable: true,
  62781. configurable: true
  62782. });
  62783. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  62784. this._renderEffects[renderEffect._name] = renderEffect;
  62785. };
  62786. // private
  62787. PostProcessRenderPipeline.prototype._rebuild = function () {
  62788. };
  62789. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62790. var renderEffects = this._renderEffects[renderEffectName];
  62791. if (!renderEffects) {
  62792. return;
  62793. }
  62794. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62795. };
  62796. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  62797. var renderEffects = this._renderEffects[renderEffectName];
  62798. if (!renderEffects) {
  62799. return;
  62800. }
  62801. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62802. };
  62803. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  62804. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62805. if (!cams) {
  62806. return;
  62807. }
  62808. var indicesToDelete = [];
  62809. var i;
  62810. for (i = 0; i < cams.length; i++) {
  62811. var camera = cams[i];
  62812. var cameraName = camera.name;
  62813. if (this._cameras.indexOf(camera) === -1) {
  62814. this._cameras[cameraName] = camera;
  62815. }
  62816. else if (unique) {
  62817. indicesToDelete.push(i);
  62818. }
  62819. }
  62820. for (i = 0; i < indicesToDelete.length; i++) {
  62821. cameras.splice(indicesToDelete[i], 1);
  62822. }
  62823. for (var renderEffectName in this._renderEffects) {
  62824. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62825. this._renderEffects[renderEffectName]._attachCameras(cams);
  62826. }
  62827. }
  62828. };
  62829. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  62830. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62831. if (!cams) {
  62832. return;
  62833. }
  62834. for (var renderEffectName in this._renderEffects) {
  62835. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62836. this._renderEffects[renderEffectName]._detachCameras(cams);
  62837. }
  62838. }
  62839. for (var i = 0; i < cams.length; i++) {
  62840. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  62841. }
  62842. };
  62843. PostProcessRenderPipeline.prototype._update = function () {
  62844. for (var renderEffectName in this._renderEffects) {
  62845. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62846. this._renderEffects[renderEffectName]._update();
  62847. }
  62848. }
  62849. for (var i = 0; i < this._cameras.length; i++) {
  62850. var cameraName = this._cameras[i].name;
  62851. if (this._renderEffectsForIsolatedPass[cameraName]) {
  62852. this._renderEffectsForIsolatedPass[cameraName]._update();
  62853. }
  62854. }
  62855. };
  62856. PostProcessRenderPipeline.prototype._reset = function () {
  62857. this._renderEffects = {};
  62858. this._renderEffectsForIsolatedPass = new Array();
  62859. };
  62860. PostProcessRenderPipeline.prototype.dispose = function () {
  62861. // Must be implemented by children
  62862. };
  62863. __decorate([
  62864. BABYLON.serialize()
  62865. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  62866. return PostProcessRenderPipeline;
  62867. }());
  62868. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  62869. })(BABYLON || (BABYLON = {}));
  62870. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  62871. var BABYLON;
  62872. (function (BABYLON) {
  62873. var DepthRenderer = /** @class */ (function () {
  62874. function DepthRenderer(scene, type) {
  62875. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  62876. var _this = this;
  62877. this._scene = scene;
  62878. var engine = scene.getEngine();
  62879. // Render target
  62880. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  62881. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62882. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62883. this._depthMap.refreshRate = 1;
  62884. this._depthMap.renderParticles = false;
  62885. this._depthMap.renderList = null;
  62886. // set default depth value to 1.0 (far away)
  62887. this._depthMap.onClearObservable.add(function (engine) {
  62888. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  62889. });
  62890. // Custom render function
  62891. var renderSubMesh = function (subMesh) {
  62892. var mesh = subMesh.getRenderingMesh();
  62893. var scene = _this._scene;
  62894. var engine = scene.getEngine();
  62895. var material = subMesh.getMaterial();
  62896. if (!material) {
  62897. return;
  62898. }
  62899. // Culling and reverse (right handed system)
  62900. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62901. // Managing instances
  62902. var batch = mesh._getInstancesRenderList(subMesh._id);
  62903. if (batch.mustReturn) {
  62904. return;
  62905. }
  62906. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62907. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  62908. engine.enableEffect(_this._effect);
  62909. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62910. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62911. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  62912. // Alpha test
  62913. if (material && material.needAlphaTesting()) {
  62914. var alphaTexture = material.getAlphaTestTexture();
  62915. if (alphaTexture) {
  62916. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62917. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62918. }
  62919. }
  62920. // Bones
  62921. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62922. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62923. }
  62924. // Draw
  62925. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62926. }
  62927. };
  62928. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62929. var index;
  62930. if (depthOnlySubMeshes.length) {
  62931. engine.setColorWrite(false);
  62932. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62933. renderSubMesh(depthOnlySubMeshes.data[index]);
  62934. }
  62935. engine.setColorWrite(true);
  62936. }
  62937. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62938. renderSubMesh(opaqueSubMeshes.data[index]);
  62939. }
  62940. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62941. renderSubMesh(alphaTestSubMeshes.data[index]);
  62942. }
  62943. };
  62944. }
  62945. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62946. var material = subMesh.getMaterial();
  62947. if (material.disableDepthWrite) {
  62948. return false;
  62949. }
  62950. var defines = [];
  62951. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62952. var mesh = subMesh.getMesh();
  62953. // Alpha test
  62954. if (material && material.needAlphaTesting()) {
  62955. defines.push("#define ALPHATEST");
  62956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62957. attribs.push(BABYLON.VertexBuffer.UVKind);
  62958. defines.push("#define UV1");
  62959. }
  62960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62961. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62962. defines.push("#define UV2");
  62963. }
  62964. }
  62965. // Bones
  62966. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62969. if (mesh.numBoneInfluencers > 4) {
  62970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62972. }
  62973. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62974. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62975. }
  62976. else {
  62977. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62978. }
  62979. // Instances
  62980. if (useInstances) {
  62981. defines.push("#define INSTANCES");
  62982. attribs.push("world0");
  62983. attribs.push("world1");
  62984. attribs.push("world2");
  62985. attribs.push("world3");
  62986. }
  62987. // Get correct effect
  62988. var join = defines.join("\n");
  62989. if (this._cachedDefines !== join) {
  62990. this._cachedDefines = join;
  62991. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62992. }
  62993. return this._effect.isReady();
  62994. };
  62995. DepthRenderer.prototype.getDepthMap = function () {
  62996. return this._depthMap;
  62997. };
  62998. // Methods
  62999. DepthRenderer.prototype.dispose = function () {
  63000. this._depthMap.dispose();
  63001. };
  63002. return DepthRenderer;
  63003. }());
  63004. BABYLON.DepthRenderer = DepthRenderer;
  63005. })(BABYLON || (BABYLON = {}));
  63006. //# sourceMappingURL=babylon.depthRenderer.js.map
  63007. var BABYLON;
  63008. (function (BABYLON) {
  63009. var SSAORenderingPipeline = /** @class */ (function (_super) {
  63010. __extends(SSAORenderingPipeline, _super);
  63011. /**
  63012. * @constructor
  63013. * @param {string} name - The rendering pipeline name
  63014. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63015. * @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 }
  63016. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63017. */
  63018. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  63019. var _this = _super.call(this, scene.getEngine(), name) || this;
  63020. // Members
  63021. /**
  63022. * The PassPostProcess id in the pipeline that contains the original scene color
  63023. * @type {string}
  63024. */
  63025. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  63026. /**
  63027. * The SSAO PostProcess id in the pipeline
  63028. * @type {string}
  63029. */
  63030. _this.SSAORenderEffect = "SSAORenderEffect";
  63031. /**
  63032. * The horizontal blur PostProcess id in the pipeline
  63033. * @type {string}
  63034. */
  63035. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  63036. /**
  63037. * The vertical blur PostProcess id in the pipeline
  63038. * @type {string}
  63039. */
  63040. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  63041. /**
  63042. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  63043. * @type {string}
  63044. */
  63045. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  63046. /**
  63047. * The output strength of the SSAO post-process. Default value is 1.0.
  63048. * @type {number}
  63049. */
  63050. _this.totalStrength = 1.0;
  63051. /**
  63052. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  63053. * @type {number}
  63054. */
  63055. _this.radius = 0.0001;
  63056. /**
  63057. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  63058. * Must not be equal to fallOff and superior to fallOff.
  63059. * Default value is 0.975
  63060. * @type {number}
  63061. */
  63062. _this.area = 0.0075;
  63063. /**
  63064. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  63065. * Must not be equal to area and inferior to area.
  63066. * Default value is 0.0
  63067. * @type {number}
  63068. */
  63069. _this.fallOff = 0.000001;
  63070. /**
  63071. * The base color of the SSAO post-process
  63072. * The final result is "base + ssao" between [0, 1]
  63073. * @type {number}
  63074. */
  63075. _this.base = 0.5;
  63076. _this._firstUpdate = true;
  63077. _this._scene = scene;
  63078. // Set up assets
  63079. _this._createRandomTexture();
  63080. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63081. var ssaoRatio = ratio.ssaoRatio || ratio;
  63082. var combineRatio = ratio.combineRatio || ratio;
  63083. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  63084. _this._createSSAOPostProcess(ssaoRatio);
  63085. _this._createBlurPostProcess(ssaoRatio);
  63086. _this._createSSAOCombinePostProcess(combineRatio);
  63087. // Set up pipeline
  63088. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  63089. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  63090. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  63091. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  63092. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  63093. // Finish
  63094. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63095. if (cameras)
  63096. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63097. return _this;
  63098. }
  63099. // Public Methods
  63100. /**
  63101. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63102. */
  63103. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63104. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63105. for (var i = 0; i < this._scene.cameras.length; i++) {
  63106. var camera = this._scene.cameras[i];
  63107. this._originalColorPostProcess.dispose(camera);
  63108. this._ssaoPostProcess.dispose(camera);
  63109. this._blurHPostProcess.dispose(camera);
  63110. this._blurVPostProcess.dispose(camera);
  63111. this._ssaoCombinePostProcess.dispose(camera);
  63112. }
  63113. this._randomTexture.dispose();
  63114. if (disableDepthRender)
  63115. this._scene.disableDepthRenderer();
  63116. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63117. _super.prototype.dispose.call(this);
  63118. };
  63119. // Private Methods
  63120. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  63121. var _this = this;
  63122. var size = 16;
  63123. 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);
  63124. 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);
  63125. this._blurHPostProcess.onActivateObservable.add(function () {
  63126. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  63127. _this._blurHPostProcess.kernel = size * dw;
  63128. });
  63129. this._blurVPostProcess.onActivateObservable.add(function () {
  63130. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  63131. _this._blurVPostProcess.kernel = size * dw;
  63132. });
  63133. };
  63134. SSAORenderingPipeline.prototype._rebuild = function () {
  63135. this._firstUpdate = true;
  63136. _super.prototype._rebuild.call(this);
  63137. };
  63138. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63139. var _this = this;
  63140. var numSamples = 16;
  63141. var sampleSphere = [
  63142. 0.5381, 0.1856, -0.4319,
  63143. 0.1379, 0.2486, 0.4430,
  63144. 0.3371, 0.5679, -0.0057,
  63145. -0.6999, -0.0451, -0.0019,
  63146. 0.0689, -0.1598, -0.8547,
  63147. 0.0560, 0.0069, -0.1843,
  63148. -0.0146, 0.1402, 0.0762,
  63149. 0.0100, -0.1924, -0.0344,
  63150. -0.3577, -0.5301, -0.4358,
  63151. -0.3169, 0.1063, 0.0158,
  63152. 0.0103, -0.5869, 0.0046,
  63153. -0.0897, -0.4940, 0.3287,
  63154. 0.7119, -0.0154, -0.0918,
  63155. -0.0533, 0.0596, -0.5411,
  63156. 0.0352, -0.0631, 0.5460,
  63157. -0.4776, 0.2847, -0.0271
  63158. ];
  63159. var samplesFactor = 1.0 / numSamples;
  63160. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  63161. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63162. "area", "fallOff", "base", "range", "viewport"
  63163. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63164. this._ssaoPostProcess.onApply = function (effect) {
  63165. if (_this._firstUpdate) {
  63166. effect.setArray3("sampleSphere", sampleSphere);
  63167. effect.setFloat("samplesFactor", samplesFactor);
  63168. effect.setFloat("randTextureTiles", 4.0);
  63169. }
  63170. effect.setFloat("totalStrength", _this.totalStrength);
  63171. effect.setFloat("radius", _this.radius);
  63172. effect.setFloat("area", _this.area);
  63173. effect.setFloat("fallOff", _this.fallOff);
  63174. effect.setFloat("base", _this.base);
  63175. effect.setTexture("textureSampler", _this._depthTexture);
  63176. effect.setTexture("randomSampler", _this._randomTexture);
  63177. };
  63178. };
  63179. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63180. var _this = this;
  63181. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63182. this._ssaoCombinePostProcess.onApply = function (effect) {
  63183. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63184. };
  63185. };
  63186. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  63187. var size = 512;
  63188. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63189. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63190. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63191. var context = this._randomTexture.getContext();
  63192. var rand = function (min, max) {
  63193. return Math.random() * (max - min) + min;
  63194. };
  63195. var randVector = BABYLON.Vector3.Zero();
  63196. for (var x = 0; x < size; x++) {
  63197. for (var y = 0; y < size; y++) {
  63198. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  63199. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  63200. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  63201. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63202. context.fillRect(x, y, 1, 1);
  63203. }
  63204. }
  63205. this._randomTexture.update(false);
  63206. };
  63207. __decorate([
  63208. BABYLON.serialize()
  63209. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  63210. __decorate([
  63211. BABYLON.serialize()
  63212. ], SSAORenderingPipeline.prototype, "radius", void 0);
  63213. __decorate([
  63214. BABYLON.serialize()
  63215. ], SSAORenderingPipeline.prototype, "area", void 0);
  63216. __decorate([
  63217. BABYLON.serialize()
  63218. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  63219. __decorate([
  63220. BABYLON.serialize()
  63221. ], SSAORenderingPipeline.prototype, "base", void 0);
  63222. return SSAORenderingPipeline;
  63223. }(BABYLON.PostProcessRenderPipeline));
  63224. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  63225. })(BABYLON || (BABYLON = {}));
  63226. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  63227. var BABYLON;
  63228. (function (BABYLON) {
  63229. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  63230. __extends(SSAO2RenderingPipeline, _super);
  63231. /**
  63232. * @constructor
  63233. * @param {string} name - The rendering pipeline name
  63234. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63235. * @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 }
  63236. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63237. */
  63238. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  63239. var _this = _super.call(this, scene.getEngine(), name) || this;
  63240. // Members
  63241. /**
  63242. * The PassPostProcess id in the pipeline that contains the original scene color
  63243. * @type {string}
  63244. */
  63245. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  63246. /**
  63247. * The SSAO PostProcess id in the pipeline
  63248. * @type {string}
  63249. */
  63250. _this.SSAORenderEffect = "SSAORenderEffect";
  63251. /**
  63252. * The horizontal blur PostProcess id in the pipeline
  63253. * @type {string}
  63254. */
  63255. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  63256. /**
  63257. * The vertical blur PostProcess id in the pipeline
  63258. * @type {string}
  63259. */
  63260. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  63261. /**
  63262. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  63263. * @type {string}
  63264. */
  63265. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  63266. /**
  63267. * The output strength of the SSAO post-process. Default value is 1.0.
  63268. * @type {number}
  63269. */
  63270. _this.totalStrength = 1.0;
  63271. /**
  63272. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  63273. * @type {number}
  63274. */
  63275. _this.maxZ = 100.0;
  63276. /**
  63277. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  63278. * @type {number}
  63279. */
  63280. _this.minZAspect = 0.2;
  63281. /**
  63282. * Number of samples used for the SSAO calculations. Default value is 8
  63283. * @type {number}
  63284. */
  63285. _this._samples = 8;
  63286. /**
  63287. * Are we using bilateral blur ?
  63288. * @type {boolean}
  63289. */
  63290. _this._expensiveBlur = true;
  63291. /**
  63292. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  63293. * @type {number}
  63294. */
  63295. _this.radius = 2.0;
  63296. /**
  63297. * The base color of the SSAO post-process
  63298. * The final result is "base + ssao" between [0, 1]
  63299. * @type {number}
  63300. */
  63301. _this.base = 0.1;
  63302. _this._firstUpdate = true;
  63303. _this._scene = scene;
  63304. if (!_this.isSupported) {
  63305. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  63306. return _this;
  63307. }
  63308. var ssaoRatio = ratio.ssaoRatio || ratio;
  63309. var blurRatio = ratio.blurRatio || ratio;
  63310. // Set up assets
  63311. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  63312. _this._createRandomTexture();
  63313. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  63314. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  63315. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  63316. _this._createSSAOPostProcess(1.0);
  63317. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  63318. _this._createSSAOCombinePostProcess(blurRatio);
  63319. // Set up pipeline
  63320. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  63321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  63322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  63323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  63324. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  63325. // Finish
  63326. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63327. if (cameras)
  63328. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63329. return _this;
  63330. }
  63331. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  63332. get: function () {
  63333. return this._samples;
  63334. },
  63335. set: function (n) {
  63336. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  63337. this._samples = n;
  63338. this._sampleSphere = this._generateHemisphere();
  63339. this._firstUpdate = true;
  63340. },
  63341. enumerable: true,
  63342. configurable: true
  63343. });
  63344. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  63345. get: function () {
  63346. return this._expensiveBlur;
  63347. },
  63348. set: function (b) {
  63349. 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"]);
  63350. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  63351. this._expensiveBlur = b;
  63352. this._firstUpdate = true;
  63353. },
  63354. enumerable: true,
  63355. configurable: true
  63356. });
  63357. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  63358. /**
  63359. * Support test.
  63360. * @type {boolean}
  63361. */
  63362. get: function () {
  63363. var engine = BABYLON.Engine.LastCreatedEngine;
  63364. if (!engine) {
  63365. return false;
  63366. }
  63367. return engine.getCaps().drawBuffersExtension;
  63368. },
  63369. enumerable: true,
  63370. configurable: true
  63371. });
  63372. // Public Methods
  63373. /**
  63374. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63375. */
  63376. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  63377. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  63378. for (var i = 0; i < this._scene.cameras.length; i++) {
  63379. var camera = this._scene.cameras[i];
  63380. this._originalColorPostProcess.dispose(camera);
  63381. this._ssaoPostProcess.dispose(camera);
  63382. this._blurHPostProcess.dispose(camera);
  63383. this._blurVPostProcess.dispose(camera);
  63384. this._ssaoCombinePostProcess.dispose(camera);
  63385. }
  63386. this._randomTexture.dispose();
  63387. if (disableGeometryBufferRenderer)
  63388. this._scene.disableGeometryBufferRenderer();
  63389. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63390. _super.prototype.dispose.call(this);
  63391. };
  63392. // Private Methods
  63393. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  63394. var _this = this;
  63395. this._samplerOffsets = [];
  63396. var expensive = this.expensiveBlur;
  63397. for (var i = -8; i < 8; i++) {
  63398. this._samplerOffsets.push(i * 2 + 0.5);
  63399. }
  63400. 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");
  63401. this._blurHPostProcess.onApply = function (effect) {
  63402. if (!_this._scene.activeCamera) {
  63403. return;
  63404. }
  63405. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  63406. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63407. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63408. effect.setFloat("radius", _this.radius);
  63409. effect.setTexture("depthSampler", _this._depthTexture);
  63410. if (_this._firstUpdate) {
  63411. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63412. }
  63413. };
  63414. 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");
  63415. this._blurVPostProcess.onApply = function (effect) {
  63416. if (!_this._scene.activeCamera) {
  63417. return;
  63418. }
  63419. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  63420. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63421. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63422. effect.setFloat("radius", _this.radius);
  63423. effect.setTexture("depthSampler", _this._depthTexture);
  63424. if (_this._firstUpdate) {
  63425. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63426. _this._firstUpdate = false;
  63427. }
  63428. };
  63429. };
  63430. SSAO2RenderingPipeline.prototype._rebuild = function () {
  63431. this._firstUpdate = true;
  63432. _super.prototype._rebuild.call(this);
  63433. };
  63434. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  63435. var numSamples = this.samples;
  63436. var result = [];
  63437. var vector, scale;
  63438. var rand = function (min, max) {
  63439. return Math.random() * (max - min) + min;
  63440. };
  63441. var i = 0;
  63442. while (i < numSamples) {
  63443. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  63444. vector.normalize();
  63445. scale = i / numSamples;
  63446. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  63447. vector.scaleInPlace(scale);
  63448. result.push(vector.x, vector.y, vector.z);
  63449. i++;
  63450. }
  63451. return result;
  63452. };
  63453. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63454. var _this = this;
  63455. var numSamples = this.samples;
  63456. this._sampleSphere = this._generateHemisphere();
  63457. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  63458. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63459. "base", "range", "projection", "near", "far", "texelSize",
  63460. "xViewport", "yViewport", "maxZ", "minZAspect"
  63461. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63462. this._ssaoPostProcess.onApply = function (effect) {
  63463. if (_this._firstUpdate) {
  63464. effect.setArray3("sampleSphere", _this._sampleSphere);
  63465. effect.setFloat("randTextureTiles", 4.0);
  63466. }
  63467. if (!_this._scene.activeCamera) {
  63468. return;
  63469. }
  63470. effect.setFloat("samplesFactor", 1 / _this.samples);
  63471. effect.setFloat("totalStrength", _this.totalStrength);
  63472. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  63473. effect.setFloat("radius", _this.radius);
  63474. effect.setFloat("maxZ", _this.maxZ);
  63475. effect.setFloat("minZAspect", _this.minZAspect);
  63476. effect.setFloat("base", _this.base);
  63477. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63478. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63479. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  63480. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  63481. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  63482. effect.setTexture("textureSampler", _this._depthTexture);
  63483. effect.setTexture("normalSampler", _this._normalTexture);
  63484. effect.setTexture("randomSampler", _this._randomTexture);
  63485. };
  63486. };
  63487. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63488. var _this = this;
  63489. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63490. this._ssaoCombinePostProcess.onApply = function (effect) {
  63491. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63492. };
  63493. };
  63494. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  63495. var size = 512;
  63496. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63497. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63498. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63499. var context = this._randomTexture.getContext();
  63500. var rand = function (min, max) {
  63501. return Math.random() * (max - min) + min;
  63502. };
  63503. var randVector = BABYLON.Vector3.Zero();
  63504. for (var x = 0; x < size; x++) {
  63505. for (var y = 0; y < size; y++) {
  63506. randVector.x = rand(0.0, 1.0);
  63507. randVector.y = rand(0.0, 1.0);
  63508. randVector.z = 0.0;
  63509. randVector.normalize();
  63510. randVector.scaleInPlace(255);
  63511. randVector.x = Math.floor(randVector.x);
  63512. randVector.y = Math.floor(randVector.y);
  63513. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63514. context.fillRect(x, y, 1, 1);
  63515. }
  63516. }
  63517. this._randomTexture.update(false);
  63518. };
  63519. __decorate([
  63520. BABYLON.serialize()
  63521. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  63522. __decorate([
  63523. BABYLON.serialize()
  63524. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  63525. __decorate([
  63526. BABYLON.serialize()
  63527. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  63528. __decorate([
  63529. BABYLON.serialize("samples")
  63530. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  63531. __decorate([
  63532. BABYLON.serialize("expensiveBlur")
  63533. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  63534. __decorate([
  63535. BABYLON.serialize()
  63536. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  63537. __decorate([
  63538. BABYLON.serialize()
  63539. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  63540. return SSAO2RenderingPipeline;
  63541. }(BABYLON.PostProcessRenderPipeline));
  63542. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  63543. })(BABYLON || (BABYLON = {}));
  63544. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  63545. // BABYLON.JS Chromatic Aberration GLSL Shader
  63546. // Author: Olivier Guyot
  63547. // Separates very slightly R, G and B colors on the edges of the screen
  63548. // Inspired by Francois Tarlier & Martins Upitis
  63549. var BABYLON;
  63550. (function (BABYLON) {
  63551. var LensRenderingPipeline = /** @class */ (function (_super) {
  63552. __extends(LensRenderingPipeline, _super);
  63553. /**
  63554. * @constructor
  63555. *
  63556. * Effect parameters are as follow:
  63557. * {
  63558. * chromatic_aberration: number; // from 0 to x (1 for realism)
  63559. * edge_blur: number; // from 0 to x (1 for realism)
  63560. * distortion: number; // from 0 to x (1 for realism)
  63561. * grain_amount: number; // from 0 to 1
  63562. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  63563. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  63564. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  63565. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  63566. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  63567. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  63568. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  63569. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  63570. * }
  63571. * Note: if an effect parameter is unset, effect is disabled
  63572. *
  63573. * @param {string} name - The rendering pipeline name
  63574. * @param {object} parameters - An object containing all parameters (see above)
  63575. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63576. * @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)
  63577. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63578. */
  63579. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  63580. if (ratio === void 0) { ratio = 1.0; }
  63581. var _this = _super.call(this, scene.getEngine(), name) || this;
  63582. // Lens effects can be of the following:
  63583. // - chromatic aberration (slight shift of RGB colors)
  63584. // - blur on the edge of the lens
  63585. // - lens distortion
  63586. // - depth-of-field blur & highlights enhancing
  63587. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  63588. // - grain effect (noise or custom texture)
  63589. // Two additional texture samplers are needed:
  63590. // - depth map (for depth-of-field)
  63591. // - grain texture
  63592. /**
  63593. * The chromatic aberration PostProcess id in the pipeline
  63594. * @type {string}
  63595. */
  63596. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  63597. /**
  63598. * The highlights enhancing PostProcess id in the pipeline
  63599. * @type {string}
  63600. */
  63601. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  63602. /**
  63603. * The depth-of-field PostProcess id in the pipeline
  63604. * @type {string}
  63605. */
  63606. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  63607. _this._scene = scene;
  63608. // Fetch texture samplers
  63609. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63610. if (parameters.grain_texture) {
  63611. _this._grainTexture = parameters.grain_texture;
  63612. }
  63613. else {
  63614. _this._createGrainTexture();
  63615. }
  63616. // save parameters
  63617. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  63618. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  63619. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  63620. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  63621. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  63622. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  63623. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  63624. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  63625. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  63626. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  63627. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  63628. // Create effects
  63629. _this._createChromaticAberrationPostProcess(ratio);
  63630. _this._createHighlightsPostProcess(ratio);
  63631. _this._createDepthOfFieldPostProcess(ratio / 4);
  63632. // Set up pipeline
  63633. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  63634. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  63635. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  63636. if (_this._highlightsGain === -1) {
  63637. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  63638. }
  63639. // Finish
  63640. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63641. if (cameras) {
  63642. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63643. }
  63644. return _this;
  63645. }
  63646. // public methods (self explanatory)
  63647. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  63648. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  63649. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  63650. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  63651. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  63652. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  63653. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  63654. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  63655. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  63656. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  63657. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  63658. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  63659. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  63660. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  63661. };
  63662. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  63663. this._highlightsPostProcess.updateEffect();
  63664. };
  63665. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  63666. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  63667. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  63668. this._highlightsGain = amount;
  63669. };
  63670. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  63671. if (this._highlightsGain === -1) {
  63672. this._highlightsGain = 1.0;
  63673. }
  63674. this._highlightsThreshold = amount;
  63675. };
  63676. LensRenderingPipeline.prototype.disableHighlights = function () {
  63677. this._highlightsGain = -1;
  63678. };
  63679. /**
  63680. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  63681. */
  63682. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63683. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63684. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63685. this._chromaticAberrationPostProcess = null;
  63686. this._highlightsPostProcess = null;
  63687. this._depthOfFieldPostProcess = null;
  63688. this._grainTexture.dispose();
  63689. if (disableDepthRender)
  63690. this._scene.disableDepthRenderer();
  63691. };
  63692. // colors shifting and distortion
  63693. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  63694. var _this = this;
  63695. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  63696. [], // samplers
  63697. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63698. this._chromaticAberrationPostProcess.onApply = function (effect) {
  63699. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  63700. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63701. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63702. };
  63703. };
  63704. // highlights enhancing
  63705. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  63706. var _this = this;
  63707. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  63708. [], // samplers
  63709. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  63710. this._highlightsPostProcess.onApply = function (effect) {
  63711. effect.setFloat('gain', _this._highlightsGain);
  63712. effect.setFloat('threshold', _this._highlightsThreshold);
  63713. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  63714. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63715. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63716. };
  63717. };
  63718. // colors shifting and distortion
  63719. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  63720. var _this = this;
  63721. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  63722. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  63723. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  63724. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63725. this._depthOfFieldPostProcess.onApply = function (effect) {
  63726. effect.setTexture("depthSampler", _this._depthTexture);
  63727. effect.setTexture("grainSampler", _this._grainTexture);
  63728. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  63729. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  63730. effect.setFloat('grain_amount', _this._grainAmount);
  63731. effect.setBool('blur_noise', _this._blurNoise);
  63732. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63733. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63734. effect.setFloat('distortion', _this._distortion);
  63735. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63736. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63737. effect.setFloat('aperture', _this._dofAperture);
  63738. effect.setFloat('darken', _this._dofDarken);
  63739. effect.setFloat('edge_blur', _this._edgeBlur);
  63740. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63741. if (_this._scene.activeCamera) {
  63742. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63743. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63744. }
  63745. };
  63746. };
  63747. // creates a black and white random noise texture, 512x512
  63748. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63749. var size = 512;
  63750. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63751. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63752. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63753. var context = this._grainTexture.getContext();
  63754. var rand = function (min, max) {
  63755. return Math.random() * (max - min) + min;
  63756. };
  63757. var value;
  63758. for (var x = 0; x < size; x++) {
  63759. for (var y = 0; y < size; y++) {
  63760. value = Math.floor(rand(0.42, 0.58) * 255);
  63761. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63762. context.fillRect(x, y, 1, 1);
  63763. }
  63764. }
  63765. this._grainTexture.update(false);
  63766. };
  63767. return LensRenderingPipeline;
  63768. }(BABYLON.PostProcessRenderPipeline));
  63769. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63770. })(BABYLON || (BABYLON = {}));
  63771. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63772. var BABYLON;
  63773. (function (BABYLON) {
  63774. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63775. __extends(StandardRenderingPipeline, _super);
  63776. /**
  63777. * @constructor
  63778. * @param {string} name - The rendering pipeline name
  63779. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63780. * @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)
  63781. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63782. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63783. */
  63784. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63785. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63786. var _this = _super.call(this, scene.getEngine(), name) || this;
  63787. _this.downSampleX4PostProcess = null;
  63788. _this.brightPassPostProcess = null;
  63789. _this.blurHPostProcesses = [];
  63790. _this.blurVPostProcesses = [];
  63791. _this.textureAdderPostProcess = null;
  63792. _this.volumetricLightPostProcess = null;
  63793. _this.volumetricLightSmoothXPostProcess = null;
  63794. _this.volumetricLightSmoothYPostProcess = null;
  63795. _this.volumetricLightMergePostProces = null;
  63796. _this.volumetricLightFinalPostProcess = null;
  63797. _this.luminancePostProcess = null;
  63798. _this.luminanceDownSamplePostProcesses = [];
  63799. _this.hdrPostProcess = null;
  63800. _this.textureAdderFinalPostProcess = null;
  63801. _this.lensFlareFinalPostProcess = null;
  63802. _this.hdrFinalPostProcess = null;
  63803. _this.lensFlarePostProcess = null;
  63804. _this.lensFlareComposePostProcess = null;
  63805. _this.motionBlurPostProcess = null;
  63806. _this.depthOfFieldPostProcess = null;
  63807. // Values
  63808. _this.brightThreshold = 1.0;
  63809. _this.blurWidth = 512.0;
  63810. _this.horizontalBlur = false;
  63811. _this.exposure = 1.0;
  63812. _this.lensTexture = null;
  63813. _this.volumetricLightCoefficient = 0.2;
  63814. _this.volumetricLightPower = 4.0;
  63815. _this.volumetricLightBlurScale = 64.0;
  63816. _this.sourceLight = null;
  63817. _this.hdrMinimumLuminance = 1.0;
  63818. _this.hdrDecreaseRate = 0.5;
  63819. _this.hdrIncreaseRate = 0.5;
  63820. _this.lensColorTexture = null;
  63821. _this.lensFlareStrength = 20.0;
  63822. _this.lensFlareGhostDispersal = 1.4;
  63823. _this.lensFlareHaloWidth = 0.7;
  63824. _this.lensFlareDistortionStrength = 16.0;
  63825. _this.lensStarTexture = null;
  63826. _this.lensFlareDirtTexture = null;
  63827. _this.depthOfFieldDistance = 10.0;
  63828. _this.depthOfFieldBlurWidth = 64.0;
  63829. _this.motionStrength = 1.0;
  63830. // IAnimatable
  63831. _this.animations = [];
  63832. _this._currentDepthOfFieldSource = null;
  63833. _this._hdrCurrentLuminance = 1.0;
  63834. // Getters and setters
  63835. _this._bloomEnabled = true;
  63836. _this._depthOfFieldEnabled = false;
  63837. _this._vlsEnabled = false;
  63838. _this._lensFlareEnabled = false;
  63839. _this._hdrEnabled = false;
  63840. _this._motionBlurEnabled = false;
  63841. _this._motionBlurSamples = 64.0;
  63842. _this._volumetricLightStepsCount = 50.0;
  63843. _this._cameras = cameras || [];
  63844. // Initialize
  63845. _this._scene = scene;
  63846. _this._basePostProcess = originalPostProcess;
  63847. _this._ratio = ratio;
  63848. // Misc
  63849. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63850. // Finish
  63851. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63852. _this._buildPipeline();
  63853. return _this;
  63854. }
  63855. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  63856. get: function () {
  63857. return this._bloomEnabled;
  63858. },
  63859. set: function (enabled) {
  63860. if (this._bloomEnabled === enabled) {
  63861. return;
  63862. }
  63863. this._bloomEnabled = enabled;
  63864. this._buildPipeline();
  63865. },
  63866. enumerable: true,
  63867. configurable: true
  63868. });
  63869. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63870. get: function () {
  63871. return this._depthOfFieldEnabled;
  63872. },
  63873. set: function (enabled) {
  63874. if (this._depthOfFieldEnabled === enabled) {
  63875. return;
  63876. }
  63877. this._depthOfFieldEnabled = enabled;
  63878. this._buildPipeline();
  63879. },
  63880. enumerable: true,
  63881. configurable: true
  63882. });
  63883. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63884. get: function () {
  63885. return this._lensFlareEnabled;
  63886. },
  63887. set: function (enabled) {
  63888. if (this._lensFlareEnabled === enabled) {
  63889. return;
  63890. }
  63891. this._lensFlareEnabled = enabled;
  63892. this._buildPipeline();
  63893. },
  63894. enumerable: true,
  63895. configurable: true
  63896. });
  63897. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  63898. get: function () {
  63899. return this._hdrEnabled;
  63900. },
  63901. set: function (enabled) {
  63902. if (this._hdrEnabled === enabled) {
  63903. return;
  63904. }
  63905. this._hdrEnabled = enabled;
  63906. this._buildPipeline();
  63907. },
  63908. enumerable: true,
  63909. configurable: true
  63910. });
  63911. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  63912. get: function () {
  63913. return this._vlsEnabled;
  63914. },
  63915. set: function (enabled) {
  63916. if (this._vlsEnabled === enabled) {
  63917. return;
  63918. }
  63919. if (enabled) {
  63920. var geometry = this._scene.enableGeometryBufferRenderer();
  63921. if (!geometry) {
  63922. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63923. return;
  63924. }
  63925. }
  63926. this._vlsEnabled = enabled;
  63927. this._buildPipeline();
  63928. },
  63929. enumerable: true,
  63930. configurable: true
  63931. });
  63932. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63933. get: function () {
  63934. return this._motionBlurEnabled;
  63935. },
  63936. set: function (enabled) {
  63937. if (this._motionBlurEnabled === enabled) {
  63938. return;
  63939. }
  63940. this._motionBlurEnabled = enabled;
  63941. this._buildPipeline();
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63947. get: function () {
  63948. return this._volumetricLightStepsCount;
  63949. },
  63950. set: function (count) {
  63951. if (this.volumetricLightPostProcess) {
  63952. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63953. }
  63954. this._volumetricLightStepsCount = count;
  63955. },
  63956. enumerable: true,
  63957. configurable: true
  63958. });
  63959. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63960. get: function () {
  63961. return this._motionBlurSamples;
  63962. },
  63963. set: function (samples) {
  63964. if (this.motionBlurPostProcess) {
  63965. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63966. }
  63967. this._motionBlurSamples = samples;
  63968. },
  63969. enumerable: true,
  63970. configurable: true
  63971. });
  63972. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63973. var _this = this;
  63974. var ratio = this._ratio;
  63975. var scene = this._scene;
  63976. this._disposePostProcesses();
  63977. this._reset();
  63978. // Create pass post-process
  63979. if (!this._basePostProcess) {
  63980. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63981. this.originalPostProcess.onApply = function (effect) {
  63982. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63983. };
  63984. }
  63985. else {
  63986. this.originalPostProcess = this._basePostProcess;
  63987. }
  63988. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63989. this._currentDepthOfFieldSource = this.originalPostProcess;
  63990. if (this._vlsEnabled) {
  63991. // Create volumetric light
  63992. this._createVolumetricLightPostProcess(scene, ratio);
  63993. // Create volumetric light final post-process
  63994. 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);
  63995. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63996. }
  63997. if (this._bloomEnabled) {
  63998. // Create down sample X4 post-process
  63999. this._createDownSampleX4PostProcess(scene, ratio / 2);
  64000. // Create bright pass post-process
  64001. this._createBrightPassPostProcess(scene, ratio / 2);
  64002. // Create gaussian blur post-processes (down sampling blurs)
  64003. this._createBlurPostProcesses(scene, ratio / 4, 1);
  64004. // Create texture adder post-process
  64005. this._createTextureAdderPostProcess(scene, ratio);
  64006. // Create depth-of-field source post-process
  64007. 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);
  64008. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  64009. }
  64010. if (this._lensFlareEnabled) {
  64011. // Create lens flare post-process
  64012. this._createLensFlarePostProcess(scene, ratio);
  64013. // Create depth-of-field source post-process post lens-flare and disable it now
  64014. 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);
  64015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  64016. }
  64017. if (this._hdrEnabled) {
  64018. // Create luminance
  64019. this._createLuminancePostProcesses(scene, this._floatTextureType);
  64020. // Create HDR
  64021. this._createHdrPostProcess(scene, ratio);
  64022. // Create depth-of-field source post-process post hdr and disable it now
  64023. 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);
  64024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  64025. }
  64026. if (this._depthOfFieldEnabled) {
  64027. // Create gaussian blur used by depth-of-field
  64028. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  64029. // Create depth-of-field post-process
  64030. this._createDepthOfFieldPostProcess(scene, ratio);
  64031. }
  64032. if (this._motionBlurEnabled) {
  64033. // Create motion blur post-process
  64034. this._createMotionBlurPostProcess(scene, ratio);
  64035. }
  64036. if (this._cameras !== null) {
  64037. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64038. }
  64039. };
  64040. // Down Sample X4 Post-Processs
  64041. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  64042. var _this = this;
  64043. var downSampleX4Offsets = new Array(32);
  64044. 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);
  64045. this.downSampleX4PostProcess.onApply = function (effect) {
  64046. var id = 0;
  64047. var width = _this.downSampleX4PostProcess.width;
  64048. var height = _this.downSampleX4PostProcess.height;
  64049. for (var i = -2; i < 2; i++) {
  64050. for (var j = -2; j < 2; j++) {
  64051. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  64052. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  64053. id += 2;
  64054. }
  64055. }
  64056. effect.setArray2("dsOffsets", downSampleX4Offsets);
  64057. };
  64058. // Add to pipeline
  64059. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  64060. };
  64061. // Brightpass Post-Process
  64062. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  64063. var _this = this;
  64064. var brightOffsets = new Array(8);
  64065. 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);
  64066. this.brightPassPostProcess.onApply = function (effect) {
  64067. var sU = (1.0 / _this.brightPassPostProcess.width);
  64068. var sV = (1.0 / _this.brightPassPostProcess.height);
  64069. brightOffsets[0] = -0.5 * sU;
  64070. brightOffsets[1] = 0.5 * sV;
  64071. brightOffsets[2] = 0.5 * sU;
  64072. brightOffsets[3] = 0.5 * sV;
  64073. brightOffsets[4] = -0.5 * sU;
  64074. brightOffsets[5] = -0.5 * sV;
  64075. brightOffsets[6] = 0.5 * sU;
  64076. brightOffsets[7] = -0.5 * sV;
  64077. effect.setArray2("dsOffsets", brightOffsets);
  64078. effect.setFloat("brightThreshold", _this.brightThreshold);
  64079. };
  64080. // Add to pipeline
  64081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  64082. };
  64083. // Create blur H&V post-processes
  64084. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  64085. var _this = this;
  64086. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  64087. var engine = scene.getEngine();
  64088. 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);
  64089. 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);
  64090. blurX.onActivateObservable.add(function () {
  64091. var dw = blurX.width / engine.getRenderWidth();
  64092. blurX.kernel = _this[blurWidthKey] * dw;
  64093. });
  64094. blurY.onActivateObservable.add(function () {
  64095. var dw = blurY.height / engine.getRenderHeight();
  64096. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  64097. });
  64098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  64099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  64100. this.blurHPostProcesses.push(blurX);
  64101. this.blurVPostProcesses.push(blurY);
  64102. };
  64103. // Create texture adder post-process
  64104. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  64105. var _this = this;
  64106. 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);
  64107. this.textureAdderPostProcess.onApply = function (effect) {
  64108. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  64109. effect.setTexture("lensSampler", _this.lensTexture);
  64110. effect.setFloat("exposure", _this.exposure);
  64111. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  64112. };
  64113. // Add to pipeline
  64114. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  64115. };
  64116. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  64117. var _this = this;
  64118. var geometryRenderer = scene.enableGeometryBufferRenderer();
  64119. geometryRenderer.enablePosition = true;
  64120. var geometry = geometryRenderer.getGBuffer();
  64121. // Base post-process
  64122. 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));
  64123. var depthValues = BABYLON.Vector2.Zero();
  64124. this.volumetricLightPostProcess.onApply = function (effect) {
  64125. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  64126. var generator = _this.sourceLight.getShadowGenerator();
  64127. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  64128. effect.setTexture("positionSampler", geometry.textures[2]);
  64129. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  64130. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  64131. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  64132. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  64133. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  64134. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  64135. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  64136. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  64137. effect.setVector2("depthValues", depthValues);
  64138. }
  64139. };
  64140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  64141. // Smooth
  64142. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  64143. // Merge
  64144. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  64145. this.volumetricLightMergePostProces.onApply = function (effect) {
  64146. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  64147. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  64148. };
  64149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  64150. };
  64151. // Create luminance
  64152. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  64153. var _this = this;
  64154. // Create luminance
  64155. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  64156. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  64157. var offsets = [];
  64158. this.luminancePostProcess.onApply = function (effect) {
  64159. var sU = (1.0 / _this.luminancePostProcess.width);
  64160. var sV = (1.0 / _this.luminancePostProcess.height);
  64161. offsets[0] = -0.5 * sU;
  64162. offsets[1] = 0.5 * sV;
  64163. offsets[2] = 0.5 * sU;
  64164. offsets[3] = 0.5 * sV;
  64165. offsets[4] = -0.5 * sU;
  64166. offsets[5] = -0.5 * sV;
  64167. offsets[6] = 0.5 * sU;
  64168. offsets[7] = -0.5 * sV;
  64169. effect.setArray2("lumOffsets", offsets);
  64170. };
  64171. // Add to pipeline
  64172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  64173. // Create down sample luminance
  64174. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  64175. var size = Math.pow(3, i);
  64176. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  64177. if (i === 0) {
  64178. defines += "#define FINAL_DOWN_SAMPLER";
  64179. }
  64180. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  64181. this.luminanceDownSamplePostProcesses.push(postProcess);
  64182. }
  64183. // Create callbacks and add effects
  64184. var lastLuminance = this.luminancePostProcess;
  64185. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  64186. var downSampleOffsets = new Array(18);
  64187. pp.onApply = function (effect) {
  64188. if (!lastLuminance) {
  64189. return;
  64190. }
  64191. var id = 0;
  64192. for (var x = -1; x < 2; x++) {
  64193. for (var y = -1; y < 2; y++) {
  64194. downSampleOffsets[id] = x / lastLuminance.width;
  64195. downSampleOffsets[id + 1] = y / lastLuminance.height;
  64196. id += 2;
  64197. }
  64198. }
  64199. effect.setArray2("dsOffsets", downSampleOffsets);
  64200. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  64201. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64202. lastLuminance = _this.luminancePostProcess;
  64203. }
  64204. else {
  64205. lastLuminance = pp;
  64206. }
  64207. };
  64208. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64209. pp.onAfterRender = function (effect) {
  64210. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  64211. 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);
  64212. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  64213. };
  64214. }
  64215. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  64216. });
  64217. };
  64218. // Create HDR post-process
  64219. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  64220. var _this = this;
  64221. 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);
  64222. var outputLiminance = 1;
  64223. var time = 0;
  64224. var lastTime = 0;
  64225. this.hdrPostProcess.onApply = function (effect) {
  64226. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  64227. time += scene.getEngine().getDeltaTime();
  64228. if (outputLiminance < 0) {
  64229. outputLiminance = _this._hdrCurrentLuminance;
  64230. }
  64231. else {
  64232. var dt = (lastTime - time) / 1000.0;
  64233. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  64234. outputLiminance += _this.hdrDecreaseRate * dt;
  64235. }
  64236. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  64237. outputLiminance -= _this.hdrIncreaseRate * dt;
  64238. }
  64239. else {
  64240. outputLiminance = _this._hdrCurrentLuminance;
  64241. }
  64242. }
  64243. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  64244. effect.setFloat("averageLuminance", outputLiminance);
  64245. lastTime = time;
  64246. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  64247. };
  64248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  64249. };
  64250. // Create lens flare post-process
  64251. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  64252. var _this = this;
  64253. 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);
  64254. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  64255. this._createBlurPostProcesses(scene, ratio / 4, 2);
  64256. 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);
  64257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  64258. var resolution = new BABYLON.Vector2(0, 0);
  64259. // Lens flare
  64260. this.lensFlarePostProcess.onApply = function (effect) {
  64261. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  64262. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  64263. effect.setFloat("strength", _this.lensFlareStrength);
  64264. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  64265. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  64266. // Shift
  64267. resolution.x = _this.lensFlarePostProcess.width;
  64268. resolution.y = _this.lensFlarePostProcess.height;
  64269. effect.setVector2("resolution", resolution);
  64270. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  64271. };
  64272. // Compose
  64273. 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);
  64274. 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);
  64275. this.lensFlareComposePostProcess.onApply = function (effect) {
  64276. if (!_this._scene.activeCamera) {
  64277. return;
  64278. }
  64279. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64280. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  64281. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  64282. // Lens start rotation matrix
  64283. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  64284. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  64285. 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));
  64286. camRot *= 4.0;
  64287. 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);
  64288. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  64289. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  64290. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  64291. };
  64292. };
  64293. // Create depth-of-field post-process
  64294. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  64295. var _this = this;
  64296. 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);
  64297. this.depthOfFieldPostProcess.onApply = function (effect) {
  64298. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64299. effect.setTexture("depthSampler", _this._getDepthTexture());
  64300. effect.setFloat("distance", _this.depthOfFieldDistance);
  64301. };
  64302. // Add to pipeline
  64303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  64304. };
  64305. // Create motion blur post-process
  64306. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  64307. var _this = this;
  64308. 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);
  64309. var motionScale = 0;
  64310. var prevViewProjection = BABYLON.Matrix.Identity();
  64311. var invViewProjection = BABYLON.Matrix.Identity();
  64312. var viewProjection = BABYLON.Matrix.Identity();
  64313. var screenSize = BABYLON.Vector2.Zero();
  64314. this.motionBlurPostProcess.onApply = function (effect) {
  64315. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  64316. viewProjection.invertToRef(invViewProjection);
  64317. effect.setMatrix("inverseViewProjection", invViewProjection);
  64318. effect.setMatrix("prevViewProjection", prevViewProjection);
  64319. prevViewProjection = viewProjection;
  64320. screenSize.x = _this.motionBlurPostProcess.width;
  64321. screenSize.y = _this.motionBlurPostProcess.height;
  64322. effect.setVector2("screenSize", screenSize);
  64323. motionScale = scene.getEngine().getFps() / 60.0;
  64324. effect.setFloat("motionScale", motionScale);
  64325. effect.setFloat("motionStrength", _this.motionStrength);
  64326. effect.setTexture("depthSampler", _this._getDepthTexture());
  64327. };
  64328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  64329. };
  64330. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  64331. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  64332. var renderer = this._scene.enableGeometryBufferRenderer();
  64333. return renderer.getGBuffer().textures[0];
  64334. }
  64335. return this._scene.enableDepthRenderer().getDepthMap();
  64336. };
  64337. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  64338. for (var i = 0; i < this._cameras.length; i++) {
  64339. var camera = this._cameras[i];
  64340. if (this.originalPostProcess) {
  64341. this.originalPostProcess.dispose(camera);
  64342. }
  64343. if (this.downSampleX4PostProcess) {
  64344. this.downSampleX4PostProcess.dispose(camera);
  64345. }
  64346. if (this.brightPassPostProcess) {
  64347. this.brightPassPostProcess.dispose(camera);
  64348. }
  64349. if (this.textureAdderPostProcess) {
  64350. this.textureAdderPostProcess.dispose(camera);
  64351. }
  64352. if (this.textureAdderFinalPostProcess) {
  64353. this.textureAdderFinalPostProcess.dispose(camera);
  64354. }
  64355. if (this.volumetricLightPostProcess) {
  64356. this.volumetricLightPostProcess.dispose(camera);
  64357. }
  64358. if (this.volumetricLightSmoothXPostProcess) {
  64359. this.volumetricLightSmoothXPostProcess.dispose(camera);
  64360. }
  64361. if (this.volumetricLightSmoothYPostProcess) {
  64362. this.volumetricLightSmoothYPostProcess.dispose(camera);
  64363. }
  64364. if (this.volumetricLightMergePostProces) {
  64365. this.volumetricLightMergePostProces.dispose(camera);
  64366. }
  64367. if (this.volumetricLightFinalPostProcess) {
  64368. this.volumetricLightFinalPostProcess.dispose(camera);
  64369. }
  64370. if (this.lensFlarePostProcess) {
  64371. this.lensFlarePostProcess.dispose(camera);
  64372. }
  64373. if (this.lensFlareComposePostProcess) {
  64374. this.lensFlareComposePostProcess.dispose(camera);
  64375. }
  64376. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  64377. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  64378. }
  64379. if (this.luminancePostProcess) {
  64380. this.luminancePostProcess.dispose(camera);
  64381. }
  64382. if (this.hdrPostProcess) {
  64383. this.hdrPostProcess.dispose(camera);
  64384. }
  64385. if (this.hdrFinalPostProcess) {
  64386. this.hdrFinalPostProcess.dispose(camera);
  64387. }
  64388. if (this.depthOfFieldPostProcess) {
  64389. this.depthOfFieldPostProcess.dispose(camera);
  64390. }
  64391. if (this.motionBlurPostProcess) {
  64392. this.motionBlurPostProcess.dispose(camera);
  64393. }
  64394. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  64395. this.blurHPostProcesses[j].dispose(camera);
  64396. }
  64397. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  64398. this.blurVPostProcesses[j].dispose(camera);
  64399. }
  64400. }
  64401. this.originalPostProcess = null;
  64402. this.downSampleX4PostProcess = null;
  64403. this.brightPassPostProcess = null;
  64404. this.textureAdderPostProcess = null;
  64405. this.textureAdderFinalPostProcess = null;
  64406. this.volumetricLightPostProcess = null;
  64407. this.volumetricLightSmoothXPostProcess = null;
  64408. this.volumetricLightSmoothYPostProcess = null;
  64409. this.volumetricLightMergePostProces = null;
  64410. this.volumetricLightFinalPostProcess = null;
  64411. this.lensFlarePostProcess = null;
  64412. this.lensFlareComposePostProcess = null;
  64413. this.luminancePostProcess = null;
  64414. this.hdrPostProcess = null;
  64415. this.hdrFinalPostProcess = null;
  64416. this.depthOfFieldPostProcess = null;
  64417. this.motionBlurPostProcess = null;
  64418. this.luminanceDownSamplePostProcesses = [];
  64419. this.blurHPostProcesses = [];
  64420. this.blurVPostProcesses = [];
  64421. };
  64422. // Dispose
  64423. StandardRenderingPipeline.prototype.dispose = function () {
  64424. this._disposePostProcesses();
  64425. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64426. _super.prototype.dispose.call(this);
  64427. };
  64428. // Serialize rendering pipeline
  64429. StandardRenderingPipeline.prototype.serialize = function () {
  64430. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64431. serializationObject.customType = "StandardRenderingPipeline";
  64432. return serializationObject;
  64433. };
  64434. /**
  64435. * Static members
  64436. */
  64437. // Parse serialized pipeline
  64438. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64439. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  64440. };
  64441. // Luminance steps
  64442. StandardRenderingPipeline.LuminanceSteps = 6;
  64443. __decorate([
  64444. BABYLON.serialize()
  64445. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  64446. __decorate([
  64447. BABYLON.serialize()
  64448. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  64449. __decorate([
  64450. BABYLON.serialize()
  64451. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  64452. __decorate([
  64453. BABYLON.serialize()
  64454. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  64455. __decorate([
  64456. BABYLON.serializeAsTexture("lensTexture")
  64457. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  64458. __decorate([
  64459. BABYLON.serialize()
  64460. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  64461. __decorate([
  64462. BABYLON.serialize()
  64463. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  64464. __decorate([
  64465. BABYLON.serialize()
  64466. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  64467. __decorate([
  64468. BABYLON.serialize()
  64469. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  64470. __decorate([
  64471. BABYLON.serialize()
  64472. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  64473. __decorate([
  64474. BABYLON.serialize()
  64475. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  64476. __decorate([
  64477. BABYLON.serializeAsTexture("lensColorTexture")
  64478. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  64479. __decorate([
  64480. BABYLON.serialize()
  64481. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  64482. __decorate([
  64483. BABYLON.serialize()
  64484. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  64485. __decorate([
  64486. BABYLON.serialize()
  64487. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  64488. __decorate([
  64489. BABYLON.serialize()
  64490. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  64491. __decorate([
  64492. BABYLON.serializeAsTexture("lensStarTexture")
  64493. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  64494. __decorate([
  64495. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  64496. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  64497. __decorate([
  64498. BABYLON.serialize()
  64499. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  64500. __decorate([
  64501. BABYLON.serialize()
  64502. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  64503. __decorate([
  64504. BABYLON.serialize()
  64505. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  64506. __decorate([
  64507. BABYLON.serialize()
  64508. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  64509. __decorate([
  64510. BABYLON.serialize()
  64511. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  64512. __decorate([
  64513. BABYLON.serialize()
  64514. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  64515. __decorate([
  64516. BABYLON.serialize()
  64517. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  64518. __decorate([
  64519. BABYLON.serialize()
  64520. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  64521. __decorate([
  64522. BABYLON.serialize()
  64523. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  64524. __decorate([
  64525. BABYLON.serialize()
  64526. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  64527. __decorate([
  64528. BABYLON.serialize()
  64529. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  64530. __decorate([
  64531. BABYLON.serialize()
  64532. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  64533. return StandardRenderingPipeline;
  64534. }(BABYLON.PostProcessRenderPipeline));
  64535. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  64536. })(BABYLON || (BABYLON = {}));
  64537. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  64538. var BABYLON;
  64539. (function (BABYLON) {
  64540. var FxaaPostProcess = /** @class */ (function (_super) {
  64541. __extends(FxaaPostProcess, _super);
  64542. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64543. if (camera === void 0) { camera = null; }
  64544. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64545. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  64546. _this.onApplyObservable.add(function (effect) {
  64547. var texelSize = _this.texelSize;
  64548. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  64549. });
  64550. return _this;
  64551. }
  64552. return FxaaPostProcess;
  64553. }(BABYLON.PostProcess));
  64554. BABYLON.FxaaPostProcess = FxaaPostProcess;
  64555. })(BABYLON || (BABYLON = {}));
  64556. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  64557. var BABYLON;
  64558. (function (BABYLON) {
  64559. /**
  64560. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  64561. */
  64562. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  64563. __extends(CircleOfConfusionPostProcess, _super);
  64564. /**
  64565. * Creates a new instance of @see CircleOfConfusionPostProcess
  64566. * @param name The name of the effect.
  64567. * @param scene The scene the effect belongs to.
  64568. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  64569. * @param options The required width/height ratio to downsize to before computing the render pass.
  64570. * @param camera The camera to apply the render pass to.
  64571. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64572. * @param engine The engine which the post process will be applied. (default: current engine)
  64573. * @param reusable If the post process can be reused on the same frame. (default: false)
  64574. * @param textureType Type of textures used when performing the post process. (default: 0)
  64575. */
  64576. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  64577. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64578. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64579. /**
  64580. * 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.
  64581. */
  64582. _this.lensSize = 50;
  64583. /**
  64584. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64585. */
  64586. _this.fStop = 1.4;
  64587. /**
  64588. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64589. */
  64590. _this.focusDistance = 2000;
  64591. /**
  64592. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  64593. */
  64594. _this.focalLength = 50;
  64595. _this.onApplyObservable.add(function (effect) {
  64596. effect.setTexture("depthSampler", depthTexture);
  64597. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  64598. var aperture = _this.lensSize / _this.fStop;
  64599. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  64600. effect.setFloat('focusDistance', _this.focusDistance);
  64601. effect.setFloat('cocPrecalculation', cocPrecalculation);
  64602. if (scene.activeCamera) {
  64603. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64604. }
  64605. });
  64606. return _this;
  64607. }
  64608. return CircleOfConfusionPostProcess;
  64609. }(BABYLON.PostProcess));
  64610. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  64611. })(BABYLON || (BABYLON = {}));
  64612. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  64613. var BABYLON;
  64614. (function (BABYLON) {
  64615. /**
  64616. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  64617. */
  64618. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  64619. __extends(DepthOfFieldMergePostProcess, _super);
  64620. /**
  64621. * Creates a new instance of @see CircleOfConfusionPostProcess
  64622. * @param name The name of the effect.
  64623. * @param original The non-blurred image to be modified
  64624. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  64625. * @param options The required width/height ratio to downsize to before computing the render pass.
  64626. * @param camera The camera to apply the render pass to.
  64627. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64628. * @param engine The engine which the post process will be applied. (default: current engine)
  64629. * @param reusable If the post process can be reused on the same frame. (default: false)
  64630. * @param textureType Type of textures used when performing the post process. (default: 0)
  64631. */
  64632. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  64633. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64634. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64635. _this.onApplyObservable.add(function (effect) {
  64636. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  64637. effect.setTextureFromPostProcess("originalSampler", original);
  64638. });
  64639. return _this;
  64640. }
  64641. return DepthOfFieldMergePostProcess;
  64642. }(BABYLON.PostProcess));
  64643. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  64644. })(BABYLON || (BABYLON = {}));
  64645. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  64646. var BABYLON;
  64647. (function (BABYLON) {
  64648. /**
  64649. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  64650. */
  64651. var DepthOfFieldEffect = /** @class */ (function (_super) {
  64652. __extends(DepthOfFieldEffect, _super);
  64653. /**
  64654. * Creates a new instance of @see DepthOfFieldEffect
  64655. * @param scene The scene the effect belongs to.
  64656. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  64657. */
  64658. function DepthOfFieldEffect(scene, pipelineTextureType) {
  64659. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  64660. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY, _this._depthOfFieldBlurX, _this._depthOfFieldMerge]; }, true) || this;
  64661. // Enable and get current depth map
  64662. var depthMap = scene.enableDepthRenderer().getDepthMap();
  64663. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  64664. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64665. // Capture circle of confusion texture
  64666. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64667. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  64668. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  64669. _this._depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this._circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64670. _this._depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64671. // Merge blurred images with original image based on circleOfConfusion
  64672. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64673. return _this;
  64674. }
  64675. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  64676. get: function () {
  64677. return this._depthOfFieldBlurX.kernel;
  64678. },
  64679. /**
  64680. * The size of the kernel to be used for the blur
  64681. */
  64682. set: function (value) {
  64683. this._depthOfFieldBlurX.kernel = value;
  64684. this._depthOfFieldBlurY.kernel = value;
  64685. },
  64686. enumerable: true,
  64687. configurable: true
  64688. });
  64689. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  64690. get: function () {
  64691. return this._circleOfConfusion.focalLength;
  64692. },
  64693. /**
  64694. * The focal the length of the camera used in the effect
  64695. */
  64696. set: function (value) {
  64697. this._circleOfConfusion.focalLength = value;
  64698. },
  64699. enumerable: true,
  64700. configurable: true
  64701. });
  64702. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  64703. get: function () {
  64704. return this._circleOfConfusion.fStop;
  64705. },
  64706. /**
  64707. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64708. */
  64709. set: function (value) {
  64710. this._circleOfConfusion.fStop = value;
  64711. },
  64712. enumerable: true,
  64713. configurable: true
  64714. });
  64715. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  64716. get: function () {
  64717. return this._circleOfConfusion.focusDistance;
  64718. },
  64719. /**
  64720. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64721. */
  64722. set: function (value) {
  64723. this._circleOfConfusion.focusDistance = value;
  64724. },
  64725. enumerable: true,
  64726. configurable: true
  64727. });
  64728. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  64729. get: function () {
  64730. return this._circleOfConfusion.lensSize;
  64731. },
  64732. /**
  64733. * 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.
  64734. */
  64735. set: function (value) {
  64736. this._circleOfConfusion.lensSize = value;
  64737. },
  64738. enumerable: true,
  64739. configurable: true
  64740. });
  64741. /**
  64742. * Disposes each of the internal effects for a given camera.
  64743. * @param camera The camera to dispose the effect on.
  64744. */
  64745. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  64746. this._depthOfFieldPass.dispose(camera);
  64747. this._circleOfConfusion.dispose(camera);
  64748. this._depthOfFieldBlurX.dispose(camera);
  64749. this._depthOfFieldBlurY.dispose(camera);
  64750. this._depthOfFieldMerge.dispose(camera);
  64751. };
  64752. return DepthOfFieldEffect;
  64753. }(BABYLON.PostProcessRenderEffect));
  64754. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  64755. })(BABYLON || (BABYLON = {}));
  64756. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  64757. var BABYLON;
  64758. (function (BABYLON) {
  64759. /**
  64760. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  64761. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  64762. */
  64763. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  64764. __extends(DefaultRenderingPipeline, _super);
  64765. /**
  64766. * @constructor
  64767. * @param {string} name - The rendering pipeline name
  64768. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64769. * @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)
  64770. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64771. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  64772. */
  64773. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  64774. if (automaticBuild === void 0) { automaticBuild = true; }
  64775. var _this = _super.call(this, scene.getEngine(), name) || this;
  64776. /**
  64777. * ID of the pass post process used for bloom,
  64778. */
  64779. _this.PassPostProcessId = "PassPostProcessEffect";
  64780. /**
  64781. * ID of the highlight post process used for bloom,
  64782. */
  64783. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  64784. /**
  64785. * ID of the blurX post process used for bloom,
  64786. */
  64787. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  64788. /**
  64789. * ID of the blurY post process used for bloom,
  64790. */
  64791. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  64792. /**
  64793. * ID of the copy back post process used for bloom,
  64794. */
  64795. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  64796. /**
  64797. * ID of the image processing post process;
  64798. */
  64799. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  64800. /**
  64801. * ID of the Fast Approximate Anti-Aliasing post process;
  64802. */
  64803. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  64804. /**
  64805. * ID of the final merge post process;
  64806. */
  64807. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  64808. /**
  64809. * Animations which can be used to tweak settings over a period of time
  64810. */
  64811. _this.animations = [];
  64812. // Values
  64813. _this._bloomEnabled = false;
  64814. _this._depthOfFieldEnabled = false;
  64815. _this._fxaaEnabled = false;
  64816. _this._imageProcessingEnabled = true;
  64817. _this._bloomScale = 0.6;
  64818. _this._buildAllowed = true;
  64819. /**
  64820. * Specifies the size of the bloom blur kernel, relative to the final output size
  64821. */
  64822. _this.bloomKernel = 64;
  64823. /**
  64824. * Specifies the weight of the bloom in the final rendering
  64825. */
  64826. _this._bloomWeight = 0.15;
  64827. _this._cameras = cameras || [];
  64828. _this._buildAllowed = automaticBuild;
  64829. // Initialize
  64830. _this._scene = scene;
  64831. var caps = _this._scene.getEngine().getCaps();
  64832. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  64833. // Misc
  64834. if (_this._hdr) {
  64835. if (caps.textureHalfFloatRender) {
  64836. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64837. }
  64838. else if (caps.textureFloatRender) {
  64839. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64840. }
  64841. }
  64842. else {
  64843. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64844. }
  64845. // Attach
  64846. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64847. _this._buildPipeline();
  64848. return _this;
  64849. }
  64850. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  64851. get: function () {
  64852. return this._bloomWeight;
  64853. },
  64854. /**
  64855. * The strength of the bloom.
  64856. */
  64857. set: function (value) {
  64858. if (this._bloomWeight === value) {
  64859. return;
  64860. }
  64861. this._bloomWeight = value;
  64862. if (this._hdr && this.copyBack) {
  64863. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  64864. }
  64865. },
  64866. enumerable: true,
  64867. configurable: true
  64868. });
  64869. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  64870. get: function () {
  64871. return this._bloomScale;
  64872. },
  64873. /**
  64874. * The scale of the bloom, lower value will provide better performance.
  64875. */
  64876. set: function (value) {
  64877. if (this._bloomScale === value) {
  64878. return;
  64879. }
  64880. this._bloomScale = value;
  64881. this._buildPipeline();
  64882. },
  64883. enumerable: true,
  64884. configurable: true
  64885. });
  64886. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  64887. get: function () {
  64888. return this._bloomEnabled;
  64889. },
  64890. /**
  64891. * Enable or disable the bloom from the pipeline
  64892. */
  64893. set: function (enabled) {
  64894. if (this._bloomEnabled === enabled) {
  64895. return;
  64896. }
  64897. this._bloomEnabled = enabled;
  64898. this._buildPipeline();
  64899. },
  64900. enumerable: true,
  64901. configurable: true
  64902. });
  64903. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  64904. /**
  64905. * If the depth of field is enabled.
  64906. */
  64907. get: function () {
  64908. return this._depthOfFieldEnabled;
  64909. },
  64910. set: function (enabled) {
  64911. if (this._depthOfFieldEnabled === enabled) {
  64912. return;
  64913. }
  64914. this._depthOfFieldEnabled = enabled;
  64915. this._buildPipeline();
  64916. },
  64917. enumerable: true,
  64918. configurable: true
  64919. });
  64920. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  64921. get: function () {
  64922. return this._fxaaEnabled;
  64923. },
  64924. /**
  64925. * If the anti aliasing is enabled.
  64926. */
  64927. set: function (enabled) {
  64928. if (this._fxaaEnabled === enabled) {
  64929. return;
  64930. }
  64931. this._fxaaEnabled = enabled;
  64932. this._buildPipeline();
  64933. },
  64934. enumerable: true,
  64935. configurable: true
  64936. });
  64937. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  64938. get: function () {
  64939. return this._imageProcessingEnabled;
  64940. },
  64941. /**
  64942. * If image processing is enabled.
  64943. */
  64944. set: function (enabled) {
  64945. if (this._imageProcessingEnabled === enabled) {
  64946. return;
  64947. }
  64948. this._imageProcessingEnabled = enabled;
  64949. this._buildPipeline();
  64950. },
  64951. enumerable: true,
  64952. configurable: true
  64953. });
  64954. /**
  64955. * Force the compilation of the entire pipeline.
  64956. */
  64957. DefaultRenderingPipeline.prototype.prepare = function () {
  64958. var previousState = this._buildAllowed;
  64959. this._buildAllowed = true;
  64960. this._buildPipeline();
  64961. this._buildAllowed = previousState;
  64962. };
  64963. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  64964. var _this = this;
  64965. if (!this._buildAllowed) {
  64966. return;
  64967. }
  64968. var engine = this._scene.getEngine();
  64969. this._disposePostProcesses();
  64970. this._reset();
  64971. if (this.bloomEnabled) {
  64972. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64973. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  64974. if (!this._hdr) {
  64975. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64976. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  64977. this.highlights.autoClear = false;
  64978. this.highlights.alwaysForcePOT = true;
  64979. }
  64980. 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);
  64981. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  64982. this.blurX.alwaysForcePOT = true;
  64983. this.blurX.autoClear = false;
  64984. this.blurX.onActivateObservable.add(function () {
  64985. var dw = _this.blurX.width / engine.getRenderWidth(true);
  64986. _this.blurX.kernel = _this.bloomKernel * dw;
  64987. });
  64988. 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);
  64989. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  64990. this.blurY.alwaysForcePOT = true;
  64991. this.blurY.autoClear = false;
  64992. this.blurY.onActivateObservable.add(function () {
  64993. var dh = _this.blurY.height / engine.getRenderHeight(true);
  64994. _this.blurY.kernel = _this.bloomKernel * dh;
  64995. });
  64996. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64997. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  64998. this.copyBack.alwaysForcePOT = true;
  64999. if (this._hdr) {
  65000. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  65001. var w = this.bloomWeight;
  65002. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  65003. }
  65004. else {
  65005. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  65006. }
  65007. this.copyBack.autoClear = false;
  65008. }
  65009. if (this.depthOfFieldEnabled) {
  65010. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  65011. this.addEffect(this.depthOfField);
  65012. }
  65013. if (this._imageProcessingEnabled) {
  65014. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65015. if (this._hdr) {
  65016. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  65017. }
  65018. else {
  65019. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  65020. }
  65021. }
  65022. if (this.fxaaEnabled) {
  65023. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65024. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  65025. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  65026. }
  65027. else if (this._hdr && this.imageProcessing) {
  65028. this.finalMerge = this.imageProcessing;
  65029. }
  65030. else {
  65031. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65032. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  65033. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  65034. }
  65035. if (this.bloomEnabled) {
  65036. if (this._hdr) {
  65037. this.copyBack.shareOutputWith(this.blurX);
  65038. if (this.imageProcessing) {
  65039. this.imageProcessing.shareOutputWith(this.pass);
  65040. this.imageProcessing.autoClear = false;
  65041. }
  65042. else if (this.fxaa) {
  65043. this.fxaa.shareOutputWith(this.pass);
  65044. }
  65045. else {
  65046. this.finalMerge.shareOutputWith(this.pass);
  65047. }
  65048. }
  65049. else {
  65050. if (this.fxaa) {
  65051. this.fxaa.shareOutputWith(this.pass);
  65052. }
  65053. else {
  65054. this.finalMerge.shareOutputWith(this.pass);
  65055. }
  65056. }
  65057. }
  65058. if (this._cameras !== null) {
  65059. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65060. }
  65061. };
  65062. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  65063. for (var i = 0; i < this._cameras.length; i++) {
  65064. var camera = this._cameras[i];
  65065. if (this.pass) {
  65066. this.pass.dispose(camera);
  65067. }
  65068. if (this.highlights) {
  65069. this.highlights.dispose(camera);
  65070. }
  65071. if (this.blurX) {
  65072. this.blurX.dispose(camera);
  65073. }
  65074. if (this.blurY) {
  65075. this.blurY.dispose(camera);
  65076. }
  65077. if (this.copyBack) {
  65078. this.copyBack.dispose(camera);
  65079. }
  65080. if (this.imageProcessing) {
  65081. this.imageProcessing.dispose(camera);
  65082. }
  65083. if (this.fxaa) {
  65084. this.fxaa.dispose(camera);
  65085. }
  65086. if (this.finalMerge) {
  65087. this.finalMerge.dispose(camera);
  65088. }
  65089. if (this.depthOfField) {
  65090. this.depthOfField.disposeEffects(camera);
  65091. }
  65092. }
  65093. this.pass = null;
  65094. this.highlights = null;
  65095. this.blurX = null;
  65096. this.blurY = null;
  65097. this.copyBack = null;
  65098. this.imageProcessing = null;
  65099. this.fxaa = null;
  65100. this.finalMerge = null;
  65101. this.depthOfField = null;
  65102. };
  65103. /**
  65104. * Dispose of the pipeline and stop all post processes
  65105. */
  65106. DefaultRenderingPipeline.prototype.dispose = function () {
  65107. this._disposePostProcesses();
  65108. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  65109. _super.prototype.dispose.call(this);
  65110. };
  65111. /**
  65112. * Serialize the rendering pipeline (Used when exporting)
  65113. * @returns the serialized object
  65114. */
  65115. DefaultRenderingPipeline.prototype.serialize = function () {
  65116. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  65117. serializationObject.customType = "DefaultRenderingPipeline";
  65118. return serializationObject;
  65119. };
  65120. /**
  65121. * Parse the serialized pipeline
  65122. * @param source Source pipeline.
  65123. * @param scene The scene to load the pipeline to.
  65124. * @param rootUrl The URL of the serialized pipeline.
  65125. * @returns An instantiated pipeline from the serialized object.
  65126. */
  65127. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  65128. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  65129. };
  65130. __decorate([
  65131. BABYLON.serialize()
  65132. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  65133. __decorate([
  65134. BABYLON.serialize()
  65135. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  65136. __decorate([
  65137. BABYLON.serialize()
  65138. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  65139. __decorate([
  65140. BABYLON.serialize()
  65141. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  65142. __decorate([
  65143. BABYLON.serialize()
  65144. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  65145. __decorate([
  65146. BABYLON.serialize()
  65147. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  65148. __decorate([
  65149. BABYLON.serialize()
  65150. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  65151. __decorate([
  65152. BABYLON.serialize()
  65153. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  65154. __decorate([
  65155. BABYLON.serialize()
  65156. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  65157. return DefaultRenderingPipeline;
  65158. }(BABYLON.PostProcessRenderPipeline));
  65159. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  65160. })(BABYLON || (BABYLON = {}));
  65161. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  65162. var BABYLON;
  65163. (function (BABYLON) {
  65164. /**
  65165. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  65166. */
  65167. var GeometryBufferRenderer = /** @class */ (function () {
  65168. /**
  65169. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  65170. * @param scene The scene the buffer belongs to
  65171. * @param ratio How big is the buffer related to the main canvas.
  65172. */
  65173. function GeometryBufferRenderer(scene, ratio) {
  65174. if (ratio === void 0) { ratio = 1; }
  65175. this._enablePosition = false;
  65176. this._scene = scene;
  65177. this._ratio = ratio;
  65178. // Render target
  65179. this._createRenderTargets();
  65180. }
  65181. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  65182. /**
  65183. * Set the render list (meshes to be rendered) used in the G buffer.
  65184. */
  65185. set: function (meshes) {
  65186. this._multiRenderTarget.renderList = meshes;
  65187. },
  65188. enumerable: true,
  65189. configurable: true
  65190. });
  65191. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  65192. /**
  65193. * Gets wether or not G buffer are supported by the running hardware.
  65194. * This requires draw buffer supports
  65195. */
  65196. get: function () {
  65197. return this._multiRenderTarget.isSupported;
  65198. },
  65199. enumerable: true,
  65200. configurable: true
  65201. });
  65202. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  65203. /**
  65204. * Gets wether or not position are enabled for the G buffer.
  65205. */
  65206. get: function () {
  65207. return this._enablePosition;
  65208. },
  65209. /**
  65210. * Sets wether or not position are enabled for the G buffer.
  65211. */
  65212. set: function (enable) {
  65213. this._enablePosition = enable;
  65214. this.dispose();
  65215. this._createRenderTargets();
  65216. },
  65217. enumerable: true,
  65218. configurable: true
  65219. });
  65220. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  65221. /**
  65222. * Gets the scene associated with the buffer.
  65223. */
  65224. get: function () {
  65225. return this._scene;
  65226. },
  65227. enumerable: true,
  65228. configurable: true
  65229. });
  65230. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  65231. /**
  65232. * Gets the ratio used by the buffer during its creation.
  65233. * How big is the buffer related to the main canvas.
  65234. */
  65235. get: function () {
  65236. return this._ratio;
  65237. },
  65238. enumerable: true,
  65239. configurable: true
  65240. });
  65241. /**
  65242. * Checks wether everything is ready to render a submesh to the G buffer.
  65243. * @param subMesh the submesh to check readiness for
  65244. * @param useInstances is the mesh drawn using instance or not
  65245. * @returns true if ready otherwise false
  65246. */
  65247. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  65248. var material = subMesh.getMaterial();
  65249. if (material && material.disableDepthWrite) {
  65250. return false;
  65251. }
  65252. var defines = [];
  65253. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65254. var mesh = subMesh.getMesh();
  65255. // Alpha test
  65256. if (material && material.needAlphaTesting()) {
  65257. defines.push("#define ALPHATEST");
  65258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65259. attribs.push(BABYLON.VertexBuffer.UVKind);
  65260. defines.push("#define UV1");
  65261. }
  65262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65263. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65264. defines.push("#define UV2");
  65265. }
  65266. }
  65267. // Buffers
  65268. if (this._enablePosition) {
  65269. defines.push("#define POSITION");
  65270. }
  65271. // Bones
  65272. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65275. if (mesh.numBoneInfluencers > 4) {
  65276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65278. }
  65279. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65280. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65281. }
  65282. else {
  65283. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65284. }
  65285. // Instances
  65286. if (useInstances) {
  65287. defines.push("#define INSTANCES");
  65288. attribs.push("world0");
  65289. attribs.push("world1");
  65290. attribs.push("world2");
  65291. attribs.push("world3");
  65292. }
  65293. // Get correct effect
  65294. var join = defines.join("\n");
  65295. if (this._cachedDefines !== join) {
  65296. this._cachedDefines = join;
  65297. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  65298. }
  65299. return this._effect.isReady();
  65300. };
  65301. /**
  65302. * Gets the current underlying G Buffer.
  65303. * @returns the buffer
  65304. */
  65305. GeometryBufferRenderer.prototype.getGBuffer = function () {
  65306. return this._multiRenderTarget;
  65307. };
  65308. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  65309. /**
  65310. * Gets the number of samples used to render the buffer (anti aliasing).
  65311. */
  65312. get: function () {
  65313. return this._multiRenderTarget.samples;
  65314. },
  65315. /**
  65316. * Sets the number of samples used to render the buffer (anti aliasing).
  65317. */
  65318. set: function (value) {
  65319. this._multiRenderTarget.samples = value;
  65320. },
  65321. enumerable: true,
  65322. configurable: true
  65323. });
  65324. /**
  65325. * Disposes the renderer and frees up associated resources.
  65326. */
  65327. GeometryBufferRenderer.prototype.dispose = function () {
  65328. this.getGBuffer().dispose();
  65329. };
  65330. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  65331. var _this = this;
  65332. var engine = this._scene.getEngine();
  65333. var count = this._enablePosition ? 3 : 2;
  65334. 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 });
  65335. if (!this.isSupported) {
  65336. return;
  65337. }
  65338. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65339. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65340. this._multiRenderTarget.refreshRate = 1;
  65341. this._multiRenderTarget.renderParticles = false;
  65342. this._multiRenderTarget.renderList = null;
  65343. // set default depth value to 1.0 (far away)
  65344. this._multiRenderTarget.onClearObservable.add(function (engine) {
  65345. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  65346. });
  65347. // Custom render function
  65348. var renderSubMesh = function (subMesh) {
  65349. var mesh = subMesh.getRenderingMesh();
  65350. var scene = _this._scene;
  65351. var engine = scene.getEngine();
  65352. var material = subMesh.getMaterial();
  65353. if (!material) {
  65354. return;
  65355. }
  65356. // Culling
  65357. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65358. // Managing instances
  65359. var batch = mesh._getInstancesRenderList(subMesh._id);
  65360. if (batch.mustReturn) {
  65361. return;
  65362. }
  65363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65364. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  65365. engine.enableEffect(_this._effect);
  65366. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65367. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65368. _this._effect.setMatrix("view", scene.getViewMatrix());
  65369. // Alpha test
  65370. if (material && material.needAlphaTesting()) {
  65371. var alphaTexture = material.getAlphaTestTexture();
  65372. if (alphaTexture) {
  65373. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65374. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65375. }
  65376. }
  65377. // Bones
  65378. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65379. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65380. }
  65381. // Draw
  65382. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65383. }
  65384. };
  65385. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65386. var index;
  65387. if (depthOnlySubMeshes.length) {
  65388. engine.setColorWrite(false);
  65389. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65390. renderSubMesh(depthOnlySubMeshes.data[index]);
  65391. }
  65392. engine.setColorWrite(true);
  65393. }
  65394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65395. renderSubMesh(opaqueSubMeshes.data[index]);
  65396. }
  65397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65398. renderSubMesh(alphaTestSubMeshes.data[index]);
  65399. }
  65400. };
  65401. };
  65402. return GeometryBufferRenderer;
  65403. }());
  65404. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  65405. })(BABYLON || (BABYLON = {}));
  65406. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  65407. var BABYLON;
  65408. (function (BABYLON) {
  65409. var RefractionPostProcess = /** @class */ (function (_super) {
  65410. __extends(RefractionPostProcess, _super);
  65411. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  65412. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  65413. _this.color = color;
  65414. _this.depth = depth;
  65415. _this.colorLevel = colorLevel;
  65416. _this.onActivateObservable.add(function (cam) {
  65417. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  65418. });
  65419. _this.onApplyObservable.add(function (effect) {
  65420. effect.setColor3("baseColor", _this.color);
  65421. effect.setFloat("depth", _this.depth);
  65422. effect.setFloat("colorLevel", _this.colorLevel);
  65423. effect.setTexture("refractionSampler", _this._refRexture);
  65424. });
  65425. return _this;
  65426. }
  65427. // Methods
  65428. RefractionPostProcess.prototype.dispose = function (camera) {
  65429. if (this._refRexture) {
  65430. this._refRexture.dispose();
  65431. }
  65432. _super.prototype.dispose.call(this, camera);
  65433. };
  65434. return RefractionPostProcess;
  65435. }(BABYLON.PostProcess));
  65436. BABYLON.RefractionPostProcess = RefractionPostProcess;
  65437. })(BABYLON || (BABYLON = {}));
  65438. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  65439. var BABYLON;
  65440. (function (BABYLON) {
  65441. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  65442. __extends(BlackAndWhitePostProcess, _super);
  65443. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  65444. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  65445. _this.degree = 1;
  65446. _this.onApplyObservable.add(function (effect) {
  65447. effect.setFloat("degree", _this.degree);
  65448. });
  65449. return _this;
  65450. }
  65451. return BlackAndWhitePostProcess;
  65452. }(BABYLON.PostProcess));
  65453. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  65454. })(BABYLON || (BABYLON = {}));
  65455. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  65456. var BABYLON;
  65457. (function (BABYLON) {
  65458. var ConvolutionPostProcess = /** @class */ (function (_super) {
  65459. __extends(ConvolutionPostProcess, _super);
  65460. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  65461. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  65462. _this.kernel = kernel;
  65463. _this.onApply = function (effect) {
  65464. effect.setFloat2("screenSize", _this.width, _this.height);
  65465. effect.setArray("kernel", _this.kernel);
  65466. };
  65467. return _this;
  65468. }
  65469. // Statics
  65470. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  65471. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  65472. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  65473. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  65474. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  65475. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  65476. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  65477. return ConvolutionPostProcess;
  65478. }(BABYLON.PostProcess));
  65479. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  65480. })(BABYLON || (BABYLON = {}));
  65481. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  65482. var BABYLON;
  65483. (function (BABYLON) {
  65484. var FilterPostProcess = /** @class */ (function (_super) {
  65485. __extends(FilterPostProcess, _super);
  65486. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  65487. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  65488. _this.kernelMatrix = kernelMatrix;
  65489. _this.onApply = function (effect) {
  65490. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  65491. };
  65492. return _this;
  65493. }
  65494. return FilterPostProcess;
  65495. }(BABYLON.PostProcess));
  65496. BABYLON.FilterPostProcess = FilterPostProcess;
  65497. })(BABYLON || (BABYLON = {}));
  65498. //# sourceMappingURL=babylon.filterPostProcess.js.map
  65499. var BABYLON;
  65500. (function (BABYLON) {
  65501. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  65502. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  65503. __extends(VolumetricLightScatteringPostProcess, _super);
  65504. /**
  65505. * @constructor
  65506. * @param {string} name - The post-process name
  65507. * @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)
  65508. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  65509. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  65510. * @param {number} samples - The post-process quality, default 100
  65511. * @param {number} samplingMode - The post-process filtering mode
  65512. * @param {BABYLON.Engine} engine - The babylon engine
  65513. * @param {boolean} reusable - If the post-process is reusable
  65514. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  65515. */
  65516. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  65517. if (samples === void 0) { samples = 100; }
  65518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65519. 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;
  65520. _this._screenCoordinates = BABYLON.Vector2.Zero();
  65521. /**
  65522. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  65523. * @type {Vector3}
  65524. */
  65525. _this.customMeshPosition = BABYLON.Vector3.Zero();
  65526. /**
  65527. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  65528. * @type {boolean}
  65529. */
  65530. _this.useCustomMeshPosition = false;
  65531. /**
  65532. * If the post-process should inverse the light scattering direction
  65533. * @type {boolean}
  65534. */
  65535. _this.invert = true;
  65536. /**
  65537. * Array containing the excluded meshes not rendered in the internal pass
  65538. */
  65539. _this.excludedMeshes = new Array();
  65540. /**
  65541. * Controls the overall intensity of the post-process
  65542. * @type {number}
  65543. */
  65544. _this.exposure = 0.3;
  65545. /**
  65546. * Dissipates each sample's contribution in range [0, 1]
  65547. * @type {number}
  65548. */
  65549. _this.decay = 0.96815;
  65550. /**
  65551. * Controls the overall intensity of each sample
  65552. * @type {number}
  65553. */
  65554. _this.weight = 0.58767;
  65555. /**
  65556. * Controls the density of each sample
  65557. * @type {number}
  65558. */
  65559. _this.density = 0.926;
  65560. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  65561. engine = scene.getEngine();
  65562. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  65563. // Configure mesh
  65564. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  65565. // Configure
  65566. _this._createPass(scene, ratio.passRatio || ratio);
  65567. _this.onActivate = function (camera) {
  65568. if (!_this.isSupported) {
  65569. _this.dispose(camera);
  65570. }
  65571. _this.onActivate = null;
  65572. };
  65573. _this.onApplyObservable.add(function (effect) {
  65574. _this._updateMeshScreenCoordinates(scene);
  65575. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  65576. effect.setFloat("exposure", _this.exposure);
  65577. effect.setFloat("decay", _this.decay);
  65578. effect.setFloat("weight", _this.weight);
  65579. effect.setFloat("density", _this.density);
  65580. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  65581. });
  65582. return _this;
  65583. }
  65584. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  65585. get: function () {
  65586. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65587. return false;
  65588. },
  65589. set: function (useDiffuseColor) {
  65590. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65591. },
  65592. enumerable: true,
  65593. configurable: true
  65594. });
  65595. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  65596. return "VolumetricLightScatteringPostProcess";
  65597. };
  65598. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  65599. var mesh = subMesh.getMesh();
  65600. // Render this.mesh as default
  65601. if (mesh === this.mesh && mesh.material) {
  65602. return mesh.material.isReady(mesh);
  65603. }
  65604. var defines = [];
  65605. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65606. var material = subMesh.getMaterial();
  65607. // Alpha test
  65608. if (material) {
  65609. if (material.needAlphaTesting()) {
  65610. defines.push("#define ALPHATEST");
  65611. }
  65612. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65613. attribs.push(BABYLON.VertexBuffer.UVKind);
  65614. defines.push("#define UV1");
  65615. }
  65616. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65617. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65618. defines.push("#define UV2");
  65619. }
  65620. }
  65621. // Bones
  65622. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65623. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65624. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65625. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65626. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  65627. }
  65628. else {
  65629. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65630. }
  65631. // Instances
  65632. if (useInstances) {
  65633. defines.push("#define INSTANCES");
  65634. attribs.push("world0");
  65635. attribs.push("world1");
  65636. attribs.push("world2");
  65637. attribs.push("world3");
  65638. }
  65639. // Get correct effect
  65640. var join = defines.join("\n");
  65641. if (this._cachedDefines !== join) {
  65642. this._cachedDefines = join;
  65643. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  65644. }
  65645. return this._volumetricLightScatteringPass.isReady();
  65646. };
  65647. /**
  65648. * Sets the new light position for light scattering effect
  65649. * @param {BABYLON.Vector3} The new custom light position
  65650. */
  65651. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  65652. this.customMeshPosition = position;
  65653. };
  65654. /**
  65655. * Returns the light position for light scattering effect
  65656. * @return {BABYLON.Vector3} The custom light position
  65657. */
  65658. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  65659. return this.customMeshPosition;
  65660. };
  65661. /**
  65662. * Disposes the internal assets and detaches the post-process from the camera
  65663. */
  65664. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  65665. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  65666. if (rttIndex !== -1) {
  65667. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  65668. }
  65669. this._volumetricLightScatteringRTT.dispose();
  65670. _super.prototype.dispose.call(this, camera);
  65671. };
  65672. /**
  65673. * Returns the render target texture used by the post-process
  65674. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  65675. */
  65676. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  65677. return this._volumetricLightScatteringRTT;
  65678. };
  65679. // Private methods
  65680. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  65681. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  65682. return true;
  65683. }
  65684. return false;
  65685. };
  65686. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  65687. var _this = this;
  65688. var engine = scene.getEngine();
  65689. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65690. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65691. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65692. this._volumetricLightScatteringRTT.renderList = null;
  65693. this._volumetricLightScatteringRTT.renderParticles = false;
  65694. var camera = this.getCamera();
  65695. if (camera) {
  65696. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65697. }
  65698. else {
  65699. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65700. }
  65701. // Custom render function for submeshes
  65702. var renderSubMesh = function (subMesh) {
  65703. var mesh = subMesh.getRenderingMesh();
  65704. if (_this._meshExcluded(mesh)) {
  65705. return;
  65706. }
  65707. var material = subMesh.getMaterial();
  65708. if (!material) {
  65709. return;
  65710. }
  65711. var scene = mesh.getScene();
  65712. var engine = scene.getEngine();
  65713. // Culling
  65714. engine.setState(material.backFaceCulling);
  65715. // Managing instances
  65716. var batch = mesh._getInstancesRenderList(subMesh._id);
  65717. if (batch.mustReturn) {
  65718. return;
  65719. }
  65720. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65721. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  65722. var effect = _this._volumetricLightScatteringPass;
  65723. if (mesh === _this.mesh) {
  65724. if (subMesh.effect) {
  65725. effect = subMesh.effect;
  65726. }
  65727. else {
  65728. effect = material.getEffect();
  65729. }
  65730. }
  65731. engine.enableEffect(effect);
  65732. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  65733. if (mesh === _this.mesh) {
  65734. material.bind(mesh.getWorldMatrix(), mesh);
  65735. }
  65736. else {
  65737. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  65738. // Alpha test
  65739. if (material && material.needAlphaTesting()) {
  65740. var alphaTexture = material.getAlphaTestTexture();
  65741. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  65742. if (alphaTexture) {
  65743. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65744. }
  65745. }
  65746. // Bones
  65747. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65748. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65749. }
  65750. }
  65751. // Draw
  65752. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  65753. }
  65754. };
  65755. // Render target texture callbacks
  65756. var savedSceneClearColor;
  65757. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  65758. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  65759. savedSceneClearColor = scene.clearColor;
  65760. scene.clearColor = sceneClearColor;
  65761. });
  65762. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  65763. scene.clearColor = savedSceneClearColor;
  65764. });
  65765. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65766. var engine = scene.getEngine();
  65767. var index;
  65768. if (depthOnlySubMeshes.length) {
  65769. engine.setColorWrite(false);
  65770. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65771. renderSubMesh(depthOnlySubMeshes.data[index]);
  65772. }
  65773. engine.setColorWrite(true);
  65774. }
  65775. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65776. renderSubMesh(opaqueSubMeshes.data[index]);
  65777. }
  65778. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65779. renderSubMesh(alphaTestSubMeshes.data[index]);
  65780. }
  65781. if (transparentSubMeshes.length) {
  65782. // Sort sub meshes
  65783. for (index = 0; index < transparentSubMeshes.length; index++) {
  65784. var submesh = transparentSubMeshes.data[index];
  65785. var boundingInfo = submesh.getBoundingInfo();
  65786. if (boundingInfo && scene.activeCamera) {
  65787. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  65788. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  65789. }
  65790. }
  65791. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  65792. sortedArray.sort(function (a, b) {
  65793. // Alpha index first
  65794. if (a._alphaIndex > b._alphaIndex) {
  65795. return 1;
  65796. }
  65797. if (a._alphaIndex < b._alphaIndex) {
  65798. return -1;
  65799. }
  65800. // Then distance to camera
  65801. if (a._distanceToCamera < b._distanceToCamera) {
  65802. return 1;
  65803. }
  65804. if (a._distanceToCamera > b._distanceToCamera) {
  65805. return -1;
  65806. }
  65807. return 0;
  65808. });
  65809. // Render sub meshes
  65810. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65811. for (index = 0; index < sortedArray.length; index++) {
  65812. renderSubMesh(sortedArray[index]);
  65813. }
  65814. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65815. }
  65816. };
  65817. };
  65818. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  65819. var transform = scene.getTransformMatrix();
  65820. var meshPosition;
  65821. if (this.useCustomMeshPosition) {
  65822. meshPosition = this.customMeshPosition;
  65823. }
  65824. else if (this.attachedNode) {
  65825. meshPosition = this.attachedNode.position;
  65826. }
  65827. else {
  65828. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  65829. }
  65830. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  65831. this._screenCoordinates.x = pos.x / this._viewPort.width;
  65832. this._screenCoordinates.y = pos.y / this._viewPort.height;
  65833. if (this.invert)
  65834. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  65835. };
  65836. // Static methods
  65837. /**
  65838. * Creates a default mesh for the Volumeric Light Scattering post-process
  65839. * @param {string} The mesh name
  65840. * @param {BABYLON.Scene} The scene where to create the mesh
  65841. * @return {BABYLON.Mesh} the default mesh
  65842. */
  65843. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  65844. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  65845. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  65846. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  65847. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  65848. mesh.material = material;
  65849. return mesh;
  65850. };
  65851. __decorate([
  65852. BABYLON.serializeAsVector3()
  65853. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  65854. __decorate([
  65855. BABYLON.serialize()
  65856. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  65857. __decorate([
  65858. BABYLON.serialize()
  65859. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  65860. __decorate([
  65861. BABYLON.serializeAsMeshReference()
  65862. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  65863. __decorate([
  65864. BABYLON.serialize()
  65865. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  65866. __decorate([
  65867. BABYLON.serialize()
  65868. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  65869. __decorate([
  65870. BABYLON.serialize()
  65871. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  65872. __decorate([
  65873. BABYLON.serialize()
  65874. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  65875. __decorate([
  65876. BABYLON.serialize()
  65877. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  65878. return VolumetricLightScatteringPostProcess;
  65879. }(BABYLON.PostProcess));
  65880. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  65881. })(BABYLON || (BABYLON = {}));
  65882. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  65883. //
  65884. // This post-process allows the modification of rendered colors by using
  65885. // a 'look-up table' (LUT). This effect is also called Color Grading.
  65886. //
  65887. // The object needs to be provided an url to a texture containing the color
  65888. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  65889. // Use an image editing software to tweak the LUT to match your needs.
  65890. //
  65891. // For an example of a color LUT, see here:
  65892. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  65893. // For explanations on color grading, see here:
  65894. // http://udn.epicgames.com/Three/ColorGrading.html
  65895. //
  65896. var BABYLON;
  65897. (function (BABYLON) {
  65898. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  65899. __extends(ColorCorrectionPostProcess, _super);
  65900. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  65901. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  65902. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65903. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  65904. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65905. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65906. _this.onApply = function (effect) {
  65907. effect.setTexture("colorTable", _this._colorTableTexture);
  65908. };
  65909. return _this;
  65910. }
  65911. return ColorCorrectionPostProcess;
  65912. }(BABYLON.PostProcess));
  65913. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  65914. })(BABYLON || (BABYLON = {}));
  65915. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  65916. var BABYLON;
  65917. (function (BABYLON) {
  65918. var TonemappingOperator;
  65919. (function (TonemappingOperator) {
  65920. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  65921. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  65922. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  65923. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  65924. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  65925. ;
  65926. var TonemapPostProcess = /** @class */ (function (_super) {
  65927. __extends(TonemapPostProcess, _super);
  65928. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  65929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65930. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65931. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  65932. _this._operator = _operator;
  65933. _this.exposureAdjustment = exposureAdjustment;
  65934. var defines = "#define ";
  65935. if (_this._operator === TonemappingOperator.Hable)
  65936. defines += "HABLE_TONEMAPPING";
  65937. else if (_this._operator === TonemappingOperator.Reinhard)
  65938. defines += "REINHARD_TONEMAPPING";
  65939. else if (_this._operator === TonemappingOperator.HejiDawson)
  65940. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  65941. else if (_this._operator === TonemappingOperator.Photographic)
  65942. defines += "PHOTOGRAPHIC_TONEMAPPING";
  65943. //sadly a second call to create the effect.
  65944. _this.updateEffect(defines);
  65945. _this.onApply = function (effect) {
  65946. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  65947. };
  65948. return _this;
  65949. }
  65950. return TonemapPostProcess;
  65951. }(BABYLON.PostProcess));
  65952. BABYLON.TonemapPostProcess = TonemapPostProcess;
  65953. })(BABYLON || (BABYLON = {}));
  65954. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  65955. var BABYLON;
  65956. (function (BABYLON) {
  65957. var DisplayPassPostProcess = /** @class */ (function (_super) {
  65958. __extends(DisplayPassPostProcess, _super);
  65959. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  65960. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  65961. }
  65962. return DisplayPassPostProcess;
  65963. }(BABYLON.PostProcess));
  65964. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  65965. })(BABYLON || (BABYLON = {}));
  65966. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  65967. var BABYLON;
  65968. (function (BABYLON) {
  65969. var HighlightsPostProcess = /** @class */ (function (_super) {
  65970. __extends(HighlightsPostProcess, _super);
  65971. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65972. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65973. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65974. }
  65975. return HighlightsPostProcess;
  65976. }(BABYLON.PostProcess));
  65977. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  65978. })(BABYLON || (BABYLON = {}));
  65979. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  65980. var BABYLON;
  65981. (function (BABYLON) {
  65982. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  65983. __extends(ImageProcessingPostProcess, _super);
  65984. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  65985. if (camera === void 0) { camera = null; }
  65986. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65987. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  65988. _this._fromLinearSpace = true;
  65989. /**
  65990. * Defines cache preventing GC.
  65991. */
  65992. _this._defines = {
  65993. IMAGEPROCESSING: false,
  65994. VIGNETTE: false,
  65995. VIGNETTEBLENDMODEMULTIPLY: false,
  65996. VIGNETTEBLENDMODEOPAQUE: false,
  65997. TONEMAPPING: false,
  65998. CONTRAST: false,
  65999. COLORCURVES: false,
  66000. COLORGRADING: false,
  66001. COLORGRADING3D: false,
  66002. FROMLINEARSPACE: false,
  66003. SAMPLER3DGREENDEPTH: false,
  66004. SAMPLER3DBGRMAP: false,
  66005. IMAGEPROCESSINGPOSTPROCESS: false,
  66006. EXPOSURE: false,
  66007. };
  66008. // Setup the configuration as forced by the constructor. This would then not force the
  66009. // scene materials output in linear space and let untouched the default forward pass.
  66010. if (imageProcessingConfiguration) {
  66011. imageProcessingConfiguration.applyByPostProcess = true;
  66012. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  66013. // This will cause the shader to be compiled
  66014. _this.fromLinearSpace = false;
  66015. }
  66016. else {
  66017. _this._attachImageProcessingConfiguration(null, true);
  66018. _this.imageProcessingConfiguration.applyByPostProcess = true;
  66019. }
  66020. _this.onApply = function (effect) {
  66021. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  66022. };
  66023. return _this;
  66024. }
  66025. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  66026. /**
  66027. * Gets the image processing configuration used either in this material.
  66028. */
  66029. get: function () {
  66030. return this._imageProcessingConfiguration;
  66031. },
  66032. /**
  66033. * Sets the Default image processing configuration used either in the this material.
  66034. *
  66035. * If sets to null, the scene one is in use.
  66036. */
  66037. set: function (value) {
  66038. this._attachImageProcessingConfiguration(value);
  66039. },
  66040. enumerable: true,
  66041. configurable: true
  66042. });
  66043. /**
  66044. * Attaches a new image processing configuration to the PBR Material.
  66045. * @param configuration
  66046. */
  66047. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  66048. var _this = this;
  66049. if (doNotBuild === void 0) { doNotBuild = false; }
  66050. if (configuration === this._imageProcessingConfiguration) {
  66051. return;
  66052. }
  66053. // Detaches observer.
  66054. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  66055. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  66056. }
  66057. // Pick the scene configuration if needed.
  66058. if (!configuration) {
  66059. var scene = null;
  66060. var engine = this.getEngine();
  66061. var camera = this.getCamera();
  66062. if (camera) {
  66063. scene = camera.getScene();
  66064. }
  66065. else if (engine && engine.scenes) {
  66066. var scenes = engine.scenes;
  66067. scene = scenes[scenes.length - 1];
  66068. }
  66069. else {
  66070. scene = BABYLON.Engine.LastCreatedScene;
  66071. }
  66072. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  66073. }
  66074. else {
  66075. this._imageProcessingConfiguration = configuration;
  66076. }
  66077. // Attaches observer.
  66078. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  66079. _this._updateParameters();
  66080. });
  66081. // Ensure the effect will be rebuilt.
  66082. if (!doNotBuild) {
  66083. this._updateParameters();
  66084. }
  66085. };
  66086. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  66087. /**
  66088. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  66089. */
  66090. get: function () {
  66091. return this.imageProcessingConfiguration.colorCurves;
  66092. },
  66093. /**
  66094. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  66095. */
  66096. set: function (value) {
  66097. this.imageProcessingConfiguration.colorCurves = value;
  66098. },
  66099. enumerable: true,
  66100. configurable: true
  66101. });
  66102. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  66103. /**
  66104. * Gets wether the color curves effect is enabled.
  66105. */
  66106. get: function () {
  66107. return this.imageProcessingConfiguration.colorCurvesEnabled;
  66108. },
  66109. /**
  66110. * Sets wether the color curves effect is enabled.
  66111. */
  66112. set: function (value) {
  66113. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  66114. },
  66115. enumerable: true,
  66116. configurable: true
  66117. });
  66118. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  66119. /**
  66120. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  66121. */
  66122. get: function () {
  66123. return this.imageProcessingConfiguration.colorGradingTexture;
  66124. },
  66125. /**
  66126. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  66127. */
  66128. set: function (value) {
  66129. this.imageProcessingConfiguration.colorGradingTexture = value;
  66130. },
  66131. enumerable: true,
  66132. configurable: true
  66133. });
  66134. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  66135. /**
  66136. * Gets wether the color grading effect is enabled.
  66137. */
  66138. get: function () {
  66139. return this.imageProcessingConfiguration.colorGradingEnabled;
  66140. },
  66141. /**
  66142. * Gets wether the color grading effect is enabled.
  66143. */
  66144. set: function (value) {
  66145. this.imageProcessingConfiguration.colorGradingEnabled = value;
  66146. },
  66147. enumerable: true,
  66148. configurable: true
  66149. });
  66150. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  66151. /**
  66152. * Gets exposure used in the effect.
  66153. */
  66154. get: function () {
  66155. return this.imageProcessingConfiguration.exposure;
  66156. },
  66157. /**
  66158. * Sets exposure used in the effect.
  66159. */
  66160. set: function (value) {
  66161. this.imageProcessingConfiguration.exposure = value;
  66162. },
  66163. enumerable: true,
  66164. configurable: true
  66165. });
  66166. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  66167. /**
  66168. * Gets wether tonemapping is enabled or not.
  66169. */
  66170. get: function () {
  66171. return this._imageProcessingConfiguration.toneMappingEnabled;
  66172. },
  66173. /**
  66174. * Sets wether tonemapping is enabled or not
  66175. */
  66176. set: function (value) {
  66177. this._imageProcessingConfiguration.toneMappingEnabled = value;
  66178. },
  66179. enumerable: true,
  66180. configurable: true
  66181. });
  66182. ;
  66183. ;
  66184. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  66185. /**
  66186. * Gets contrast used in the effect.
  66187. */
  66188. get: function () {
  66189. return this.imageProcessingConfiguration.contrast;
  66190. },
  66191. /**
  66192. * Sets contrast used in the effect.
  66193. */
  66194. set: function (value) {
  66195. this.imageProcessingConfiguration.contrast = value;
  66196. },
  66197. enumerable: true,
  66198. configurable: true
  66199. });
  66200. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  66201. /**
  66202. * Gets Vignette stretch size.
  66203. */
  66204. get: function () {
  66205. return this.imageProcessingConfiguration.vignetteStretch;
  66206. },
  66207. /**
  66208. * Sets Vignette stretch size.
  66209. */
  66210. set: function (value) {
  66211. this.imageProcessingConfiguration.vignetteStretch = value;
  66212. },
  66213. enumerable: true,
  66214. configurable: true
  66215. });
  66216. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  66217. /**
  66218. * Gets Vignette centre X Offset.
  66219. */
  66220. get: function () {
  66221. return this.imageProcessingConfiguration.vignetteCentreX;
  66222. },
  66223. /**
  66224. * Sets Vignette centre X Offset.
  66225. */
  66226. set: function (value) {
  66227. this.imageProcessingConfiguration.vignetteCentreX = value;
  66228. },
  66229. enumerable: true,
  66230. configurable: true
  66231. });
  66232. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  66233. /**
  66234. * Gets Vignette centre Y Offset.
  66235. */
  66236. get: function () {
  66237. return this.imageProcessingConfiguration.vignetteCentreY;
  66238. },
  66239. /**
  66240. * Sets Vignette centre Y Offset.
  66241. */
  66242. set: function (value) {
  66243. this.imageProcessingConfiguration.vignetteCentreY = value;
  66244. },
  66245. enumerable: true,
  66246. configurable: true
  66247. });
  66248. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  66249. /**
  66250. * Gets Vignette weight or intensity of the vignette effect.
  66251. */
  66252. get: function () {
  66253. return this.imageProcessingConfiguration.vignetteWeight;
  66254. },
  66255. /**
  66256. * Sets Vignette weight or intensity of the vignette effect.
  66257. */
  66258. set: function (value) {
  66259. this.imageProcessingConfiguration.vignetteWeight = value;
  66260. },
  66261. enumerable: true,
  66262. configurable: true
  66263. });
  66264. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  66265. /**
  66266. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66267. * if vignetteEnabled is set to true.
  66268. */
  66269. get: function () {
  66270. return this.imageProcessingConfiguration.vignetteColor;
  66271. },
  66272. /**
  66273. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66274. * if vignetteEnabled is set to true.
  66275. */
  66276. set: function (value) {
  66277. this.imageProcessingConfiguration.vignetteColor = value;
  66278. },
  66279. enumerable: true,
  66280. configurable: true
  66281. });
  66282. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  66283. /**
  66284. * Gets Camera field of view used by the Vignette effect.
  66285. */
  66286. get: function () {
  66287. return this.imageProcessingConfiguration.vignetteCameraFov;
  66288. },
  66289. /**
  66290. * Sets Camera field of view used by the Vignette effect.
  66291. */
  66292. set: function (value) {
  66293. this.imageProcessingConfiguration.vignetteCameraFov = value;
  66294. },
  66295. enumerable: true,
  66296. configurable: true
  66297. });
  66298. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  66299. /**
  66300. * Gets the vignette blend mode allowing different kind of effect.
  66301. */
  66302. get: function () {
  66303. return this.imageProcessingConfiguration.vignetteBlendMode;
  66304. },
  66305. /**
  66306. * Sets the vignette blend mode allowing different kind of effect.
  66307. */
  66308. set: function (value) {
  66309. this.imageProcessingConfiguration.vignetteBlendMode = value;
  66310. },
  66311. enumerable: true,
  66312. configurable: true
  66313. });
  66314. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  66315. /**
  66316. * Gets wether the vignette effect is enabled.
  66317. */
  66318. get: function () {
  66319. return this.imageProcessingConfiguration.vignetteEnabled;
  66320. },
  66321. /**
  66322. * Sets wether the vignette effect is enabled.
  66323. */
  66324. set: function (value) {
  66325. this.imageProcessingConfiguration.vignetteEnabled = value;
  66326. },
  66327. enumerable: true,
  66328. configurable: true
  66329. });
  66330. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  66331. /**
  66332. * Gets wether the input of the processing is in Gamma or Linear Space.
  66333. */
  66334. get: function () {
  66335. return this._fromLinearSpace;
  66336. },
  66337. /**
  66338. * Sets wether the input of the processing is in Gamma or Linear Space.
  66339. */
  66340. set: function (value) {
  66341. if (this._fromLinearSpace === value) {
  66342. return;
  66343. }
  66344. this._fromLinearSpace = value;
  66345. this._updateParameters();
  66346. },
  66347. enumerable: true,
  66348. configurable: true
  66349. });
  66350. ImageProcessingPostProcess.prototype.getClassName = function () {
  66351. return "ImageProcessingPostProcess";
  66352. };
  66353. ImageProcessingPostProcess.prototype._updateParameters = function () {
  66354. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  66355. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  66356. var defines = "";
  66357. for (var define in this._defines) {
  66358. if (this._defines[define]) {
  66359. defines += "#define " + define + ";\r\n";
  66360. }
  66361. }
  66362. var samplers = ["textureSampler"];
  66363. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  66364. var uniforms = ["scale"];
  66365. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  66366. this.updateEffect(defines, uniforms, samplers);
  66367. };
  66368. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  66369. _super.prototype.dispose.call(this, camera);
  66370. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  66371. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  66372. }
  66373. this.imageProcessingConfiguration.applyByPostProcess = false;
  66374. };
  66375. __decorate([
  66376. BABYLON.serialize()
  66377. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  66378. return ImageProcessingPostProcess;
  66379. }(BABYLON.PostProcess));
  66380. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  66381. })(BABYLON || (BABYLON = {}));
  66382. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  66383. var BABYLON;
  66384. (function (BABYLON) {
  66385. /**
  66386. * The Blur Post Process which blurs an image based on a kernel and direction.
  66387. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  66388. */
  66389. var BlurPostProcess = /** @class */ (function (_super) {
  66390. __extends(BlurPostProcess, _super);
  66391. /**
  66392. * Creates a new instance of @see BlurPostProcess
  66393. * @param name The name of the effect.
  66394. * @param direction The direction in which to blur the image.
  66395. * @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.
  66396. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66397. * @param camera The camera to apply the render pass to.
  66398. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66399. * @param engine The engine which the post process will be applied. (default: current engine)
  66400. * @param reusable If the post process can be reused on the same frame. (default: false)
  66401. * @param textureType Type of textures used when performing the post process. (default: 0)
  66402. */
  66403. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  66404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66405. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66406. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  66407. _this.direction = direction;
  66408. _this._packedFloat = false;
  66409. _this._staticDefines = "";
  66410. _this.onApplyObservable.add(function (effect) {
  66411. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  66412. });
  66413. _this.kernel = kernel;
  66414. return _this;
  66415. }
  66416. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  66417. /**
  66418. * Gets the length in pixels of the blur sample region
  66419. */
  66420. get: function () {
  66421. return this._idealKernel;
  66422. },
  66423. /**
  66424. * Sets the length in pixels of the blur sample region
  66425. */
  66426. set: function (v) {
  66427. if (this._idealKernel === v) {
  66428. return;
  66429. }
  66430. v = Math.max(v, 1);
  66431. this._idealKernel = v;
  66432. this._kernel = this._nearestBestKernel(v);
  66433. this._updateParameters();
  66434. },
  66435. enumerable: true,
  66436. configurable: true
  66437. });
  66438. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  66439. /**
  66440. * Gets wether or not the blur is unpacking/repacking floats
  66441. */
  66442. get: function () {
  66443. return this._packedFloat;
  66444. },
  66445. /**
  66446. * Sets wether or not the blur needs to unpack/repack floats
  66447. */
  66448. set: function (v) {
  66449. if (this._packedFloat === v) {
  66450. return;
  66451. }
  66452. this._packedFloat = v;
  66453. this._updateParameters();
  66454. },
  66455. enumerable: true,
  66456. configurable: true
  66457. });
  66458. BlurPostProcess.prototype._updateParameters = function () {
  66459. // Generate sampling offsets and weights
  66460. var N = this._kernel;
  66461. var centerIndex = (N - 1) / 2;
  66462. // Generate Gaussian sampling weights over kernel
  66463. var offsets = [];
  66464. var weights = [];
  66465. var totalWeight = 0;
  66466. for (var i = 0; i < N; i++) {
  66467. var u = i / (N - 1);
  66468. var w = this._gaussianWeight(u * 2.0 - 1);
  66469. offsets[i] = (i - centerIndex);
  66470. weights[i] = w;
  66471. totalWeight += w;
  66472. }
  66473. // Normalize weights
  66474. for (var i = 0; i < weights.length; i++) {
  66475. weights[i] /= totalWeight;
  66476. }
  66477. // Optimize: combine samples to take advantage of hardware linear sampling
  66478. // Walk from left to center, combining pairs (symmetrically)
  66479. var linearSamplingWeights = [];
  66480. var linearSamplingOffsets = [];
  66481. var linearSamplingMap = [];
  66482. for (var i = 0; i <= centerIndex; i += 2) {
  66483. var j = Math.min(i + 1, Math.floor(centerIndex));
  66484. var singleCenterSample = i === j;
  66485. if (singleCenterSample) {
  66486. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66487. }
  66488. else {
  66489. var sharedCell = j === centerIndex;
  66490. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  66491. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  66492. if (offsetLinear === 0) {
  66493. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66494. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  66495. }
  66496. else {
  66497. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  66498. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  66499. }
  66500. }
  66501. }
  66502. for (var i = 0; i < linearSamplingMap.length; i++) {
  66503. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  66504. linearSamplingWeights[i] = linearSamplingMap[i].w;
  66505. }
  66506. // Replace with optimized
  66507. offsets = linearSamplingOffsets;
  66508. weights = linearSamplingWeights;
  66509. // Generate shaders
  66510. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  66511. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  66512. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  66513. var defines = "";
  66514. defines += this._staticDefines;
  66515. for (var i = 0; i < varyingCount; i++) {
  66516. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  66517. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  66518. }
  66519. var depCount = 0;
  66520. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  66521. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  66522. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  66523. depCount++;
  66524. }
  66525. if (this.packedFloat) {
  66526. defines += "#define PACKEDFLOAT 1";
  66527. }
  66528. this.updateEffect(defines, null, null, {
  66529. varyingCount: varyingCount,
  66530. depCount: depCount
  66531. });
  66532. };
  66533. /**
  66534. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  66535. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  66536. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  66537. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  66538. * The gaps between physical kernels are compensated for in the weighting of the samples
  66539. * @param idealKernel Ideal blur kernel.
  66540. * @return Nearest best kernel.
  66541. */
  66542. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  66543. var v = Math.round(idealKernel);
  66544. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  66545. var k = _a[_i];
  66546. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  66547. return Math.max(k, 3);
  66548. }
  66549. }
  66550. return Math.max(v, 3);
  66551. };
  66552. /**
  66553. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  66554. * @param x The point on the Gaussian distribution to sample.
  66555. * @return the value of the Gaussian function at x.
  66556. */
  66557. BlurPostProcess.prototype._gaussianWeight = function (x) {
  66558. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  66559. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  66560. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  66561. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  66562. // truncated at around 1.3% of peak strength.
  66563. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  66564. var sigma = (1 / 3);
  66565. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  66566. var exponent = -((x * x) / (2.0 * sigma * sigma));
  66567. var weight = (1.0 / denominator) * Math.exp(exponent);
  66568. return weight;
  66569. };
  66570. /**
  66571. * Generates a string that can be used as a floating point number in GLSL.
  66572. * @param x Value to print.
  66573. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  66574. * @return GLSL float string.
  66575. */
  66576. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  66577. if (decimalFigures === void 0) { decimalFigures = 8; }
  66578. return x.toFixed(decimalFigures).replace(/0+$/, '');
  66579. };
  66580. return BlurPostProcess;
  66581. }(BABYLON.PostProcess));
  66582. BABYLON.BlurPostProcess = BlurPostProcess;
  66583. })(BABYLON || (BABYLON = {}));
  66584. //# sourceMappingURL=babylon.blurPostProcess.js.map
  66585. var BABYLON;
  66586. (function (BABYLON) {
  66587. var Bone = /** @class */ (function (_super) {
  66588. __extends(Bone, _super);
  66589. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  66590. if (parentBone === void 0) { parentBone = null; }
  66591. if (localMatrix === void 0) { localMatrix = null; }
  66592. if (restPose === void 0) { restPose = null; }
  66593. if (baseMatrix === void 0) { baseMatrix = null; }
  66594. if (index === void 0) { index = null; }
  66595. var _this = _super.call(this, name, skeleton.getScene()) || this;
  66596. _this.name = name;
  66597. _this.children = new Array();
  66598. _this.animations = new Array();
  66599. // Set this value to map this bone to a different index in the transform matrices.
  66600. // Set this value to -1 to exclude the bone from the transform matrices.
  66601. _this._index = null;
  66602. _this._worldTransform = new BABYLON.Matrix();
  66603. _this._absoluteTransform = new BABYLON.Matrix();
  66604. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  66605. _this._scaleMatrix = BABYLON.Matrix.Identity();
  66606. _this._scaleVector = BABYLON.Vector3.One();
  66607. _this._negateScaleChildren = BABYLON.Vector3.One();
  66608. _this._scalingDeterminant = 1;
  66609. _this._skeleton = skeleton;
  66610. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  66611. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  66612. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  66613. _this._index = index;
  66614. skeleton.bones.push(_this);
  66615. _this.setParent(parentBone, false);
  66616. _this._updateDifferenceMatrix();
  66617. return _this;
  66618. }
  66619. Object.defineProperty(Bone.prototype, "_matrix", {
  66620. get: function () {
  66621. return this._localMatrix;
  66622. },
  66623. set: function (val) {
  66624. if (this._localMatrix) {
  66625. this._localMatrix.copyFrom(val);
  66626. }
  66627. else {
  66628. this._localMatrix = val;
  66629. }
  66630. },
  66631. enumerable: true,
  66632. configurable: true
  66633. });
  66634. // Members
  66635. Bone.prototype.getSkeleton = function () {
  66636. return this._skeleton;
  66637. };
  66638. Bone.prototype.getParent = function () {
  66639. return this._parent;
  66640. };
  66641. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  66642. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66643. if (this._parent === parent) {
  66644. return;
  66645. }
  66646. if (this._parent) {
  66647. var index = this._parent.children.indexOf(this);
  66648. if (index !== -1) {
  66649. this._parent.children.splice(index, 1);
  66650. }
  66651. }
  66652. this._parent = parent;
  66653. if (this._parent) {
  66654. this._parent.children.push(this);
  66655. }
  66656. if (updateDifferenceMatrix) {
  66657. this._updateDifferenceMatrix();
  66658. }
  66659. };
  66660. Bone.prototype.getLocalMatrix = function () {
  66661. return this._localMatrix;
  66662. };
  66663. Bone.prototype.getBaseMatrix = function () {
  66664. return this._baseMatrix;
  66665. };
  66666. Bone.prototype.getRestPose = function () {
  66667. return this._restPose;
  66668. };
  66669. Bone.prototype.returnToRest = function () {
  66670. this.updateMatrix(this._restPose.clone());
  66671. };
  66672. Bone.prototype.getWorldMatrix = function () {
  66673. return this._worldTransform;
  66674. };
  66675. Bone.prototype.getInvertedAbsoluteTransform = function () {
  66676. return this._invertedAbsoluteTransform;
  66677. };
  66678. Bone.prototype.getAbsoluteTransform = function () {
  66679. return this._absoluteTransform;
  66680. };
  66681. Object.defineProperty(Bone.prototype, "position", {
  66682. // Properties (matches AbstractMesh properties)
  66683. get: function () {
  66684. return this.getPosition();
  66685. },
  66686. set: function (newPosition) {
  66687. this.setPosition(newPosition);
  66688. },
  66689. enumerable: true,
  66690. configurable: true
  66691. });
  66692. Object.defineProperty(Bone.prototype, "rotation", {
  66693. get: function () {
  66694. return this.getRotation();
  66695. },
  66696. set: function (newRotation) {
  66697. this.setRotation(newRotation);
  66698. },
  66699. enumerable: true,
  66700. configurable: true
  66701. });
  66702. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  66703. get: function () {
  66704. return this.getRotationQuaternion();
  66705. },
  66706. set: function (newRotation) {
  66707. this.setRotationQuaternion(newRotation);
  66708. },
  66709. enumerable: true,
  66710. configurable: true
  66711. });
  66712. Object.defineProperty(Bone.prototype, "scaling", {
  66713. get: function () {
  66714. return this.getScale();
  66715. },
  66716. set: function (newScaling) {
  66717. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  66718. },
  66719. enumerable: true,
  66720. configurable: true
  66721. });
  66722. // Methods
  66723. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  66724. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66725. this._baseMatrix = matrix.clone();
  66726. this._localMatrix = matrix.clone();
  66727. this._skeleton._markAsDirty();
  66728. if (updateDifferenceMatrix) {
  66729. this._updateDifferenceMatrix();
  66730. }
  66731. };
  66732. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  66733. if (!rootMatrix) {
  66734. rootMatrix = this._baseMatrix;
  66735. }
  66736. if (this._parent) {
  66737. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66738. }
  66739. else {
  66740. this._absoluteTransform.copyFrom(rootMatrix);
  66741. }
  66742. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  66743. for (var index = 0; index < this.children.length; index++) {
  66744. this.children[index]._updateDifferenceMatrix();
  66745. }
  66746. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  66747. };
  66748. Bone.prototype.markAsDirty = function () {
  66749. this._currentRenderId++;
  66750. this._skeleton._markAsDirty();
  66751. };
  66752. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  66753. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66754. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  66755. // all animation may be coming from a library skeleton, so may need to create animation
  66756. if (this.animations.length === 0) {
  66757. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  66758. this.animations[0].setKeys([]);
  66759. }
  66760. // get animation info / verify there is such a range from the source bone
  66761. var sourceRange = source.animations[0].getRange(rangeName);
  66762. if (!sourceRange) {
  66763. return false;
  66764. }
  66765. var from = sourceRange.from;
  66766. var to = sourceRange.to;
  66767. var sourceKeys = source.animations[0].getKeys();
  66768. // rescaling prep
  66769. var sourceBoneLength = source.length;
  66770. var sourceParent = source.getParent();
  66771. var parent = this.getParent();
  66772. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  66773. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  66774. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  66775. var destKeys = this.animations[0].getKeys();
  66776. // loop vars declaration
  66777. var orig;
  66778. var origTranslation;
  66779. var mat;
  66780. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  66781. orig = sourceKeys[key];
  66782. if (orig.frame >= from && orig.frame <= to) {
  66783. if (rescaleAsRequired) {
  66784. mat = orig.value.clone();
  66785. // scale based on parent ratio, when bone has parent
  66786. if (parentScalingReqd) {
  66787. origTranslation = mat.getTranslation();
  66788. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  66789. // scale based on skeleton dimension ratio when root bone, and value is passed
  66790. }
  66791. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  66792. origTranslation = mat.getTranslation();
  66793. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  66794. // use original when root bone, and no data for skelDimensionsRatio
  66795. }
  66796. else {
  66797. mat = orig.value;
  66798. }
  66799. }
  66800. else {
  66801. mat = orig.value;
  66802. }
  66803. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  66804. }
  66805. }
  66806. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  66807. return true;
  66808. };
  66809. /**
  66810. * Translate the bone in local or world space.
  66811. * @param vec The amount to translate the bone.
  66812. * @param space The space that the translation is in.
  66813. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66814. */
  66815. Bone.prototype.translate = function (vec, space, mesh) {
  66816. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66817. var lm = this.getLocalMatrix();
  66818. if (space == BABYLON.Space.LOCAL) {
  66819. lm.m[12] += vec.x;
  66820. lm.m[13] += vec.y;
  66821. lm.m[14] += vec.z;
  66822. }
  66823. else {
  66824. var wm = null;
  66825. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66826. if (mesh) {
  66827. wm = mesh.getWorldMatrix();
  66828. }
  66829. this._skeleton.computeAbsoluteTransforms();
  66830. var tmat = Bone._tmpMats[0];
  66831. var tvec = Bone._tmpVecs[0];
  66832. if (this._parent) {
  66833. if (mesh && wm) {
  66834. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66835. tmat.multiplyToRef(wm, tmat);
  66836. }
  66837. else {
  66838. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66839. }
  66840. }
  66841. tmat.m[12] = 0;
  66842. tmat.m[13] = 0;
  66843. tmat.m[14] = 0;
  66844. tmat.invert();
  66845. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  66846. lm.m[12] += tvec.x;
  66847. lm.m[13] += tvec.y;
  66848. lm.m[14] += tvec.z;
  66849. }
  66850. this.markAsDirty();
  66851. };
  66852. /**
  66853. * Set the postion of the bone in local or world space.
  66854. * @param position The position to set the bone.
  66855. * @param space The space that the position is in.
  66856. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66857. */
  66858. Bone.prototype.setPosition = function (position, space, mesh) {
  66859. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66860. var lm = this.getLocalMatrix();
  66861. if (space == BABYLON.Space.LOCAL) {
  66862. lm.m[12] = position.x;
  66863. lm.m[13] = position.y;
  66864. lm.m[14] = position.z;
  66865. }
  66866. else {
  66867. var wm = null;
  66868. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66869. if (mesh) {
  66870. wm = mesh.getWorldMatrix();
  66871. }
  66872. this._skeleton.computeAbsoluteTransforms();
  66873. var tmat = Bone._tmpMats[0];
  66874. var vec = Bone._tmpVecs[0];
  66875. if (this._parent) {
  66876. if (mesh && wm) {
  66877. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66878. tmat.multiplyToRef(wm, tmat);
  66879. }
  66880. else {
  66881. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66882. }
  66883. }
  66884. tmat.invert();
  66885. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  66886. lm.m[12] = vec.x;
  66887. lm.m[13] = vec.y;
  66888. lm.m[14] = vec.z;
  66889. }
  66890. this.markAsDirty();
  66891. };
  66892. /**
  66893. * Set the absolute postion of the bone (world space).
  66894. * @param position The position to set the bone.
  66895. * @param mesh The mesh that this bone is attached to.
  66896. */
  66897. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  66898. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  66899. };
  66900. /**
  66901. * Set the scale of the bone on the x, y and z axes.
  66902. * @param x The scale of the bone on the x axis.
  66903. * @param x The scale of the bone on the y axis.
  66904. * @param z The scale of the bone on the z axis.
  66905. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66906. */
  66907. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  66908. if (scaleChildren === void 0) { scaleChildren = false; }
  66909. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  66910. if (!scaleChildren) {
  66911. this._negateScaleChildren.x = 1 / x;
  66912. this._negateScaleChildren.y = 1 / y;
  66913. this._negateScaleChildren.z = 1 / z;
  66914. }
  66915. this._syncScaleVector();
  66916. }
  66917. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  66918. };
  66919. /**
  66920. * Scale the bone on the x, y and z axes.
  66921. * @param x The amount to scale the bone on the x axis.
  66922. * @param x The amount to scale the bone on the y axis.
  66923. * @param z The amount to scale the bone on the z axis.
  66924. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66925. */
  66926. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  66927. if (scaleChildren === void 0) { scaleChildren = false; }
  66928. var locMat = this.getLocalMatrix();
  66929. var origLocMat = Bone._tmpMats[0];
  66930. origLocMat.copyFrom(locMat);
  66931. var origLocMatInv = Bone._tmpMats[1];
  66932. origLocMatInv.copyFrom(origLocMat);
  66933. origLocMatInv.invert();
  66934. var scaleMat = Bone._tmpMats[2];
  66935. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  66936. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  66937. this._scaleVector.x *= x;
  66938. this._scaleVector.y *= y;
  66939. this._scaleVector.z *= z;
  66940. locMat.multiplyToRef(origLocMatInv, locMat);
  66941. locMat.multiplyToRef(scaleMat, locMat);
  66942. locMat.multiplyToRef(origLocMat, locMat);
  66943. var parent = this.getParent();
  66944. if (parent) {
  66945. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  66946. }
  66947. else {
  66948. this.getAbsoluteTransform().copyFrom(locMat);
  66949. }
  66950. var len = this.children.length;
  66951. scaleMat.invert();
  66952. for (var i = 0; i < len; i++) {
  66953. var child = this.children[i];
  66954. var cm = child.getLocalMatrix();
  66955. cm.multiplyToRef(scaleMat, cm);
  66956. var lm = child.getLocalMatrix();
  66957. lm.m[12] *= x;
  66958. lm.m[13] *= y;
  66959. lm.m[14] *= z;
  66960. }
  66961. this.computeAbsoluteTransforms();
  66962. if (scaleChildren) {
  66963. for (var i = 0; i < len; i++) {
  66964. this.children[i].scale(x, y, z, scaleChildren);
  66965. }
  66966. }
  66967. this.markAsDirty();
  66968. };
  66969. /**
  66970. * Set the yaw, pitch, and roll of the bone in local or world space.
  66971. * @param yaw The rotation of the bone on the y axis.
  66972. * @param pitch The rotation of the bone on the x axis.
  66973. * @param roll The rotation of the bone on the z axis.
  66974. * @param space The space that the axes of rotation are in.
  66975. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66976. */
  66977. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  66978. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66979. var rotMat = Bone._tmpMats[0];
  66980. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  66981. var rotMatInv = Bone._tmpMats[1];
  66982. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66983. rotMatInv.multiplyToRef(rotMat, rotMat);
  66984. this._rotateWithMatrix(rotMat, space, mesh);
  66985. };
  66986. /**
  66987. * Rotate the bone on an axis in local or world space.
  66988. * @param axis The axis to rotate the bone on.
  66989. * @param amount The amount to rotate the bone.
  66990. * @param space The space that the axis is in.
  66991. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66992. */
  66993. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  66994. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66995. var rmat = Bone._tmpMats[0];
  66996. rmat.m[12] = 0;
  66997. rmat.m[13] = 0;
  66998. rmat.m[14] = 0;
  66999. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  67000. this._rotateWithMatrix(rmat, space, mesh);
  67001. };
  67002. /**
  67003. * Set the rotation of the bone to a particular axis angle in local or world space.
  67004. * @param axis The axis to rotate the bone on.
  67005. * @param angle The angle that the bone should be rotated to.
  67006. * @param space The space that the axis is in.
  67007. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67008. */
  67009. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  67010. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67011. var rotMat = Bone._tmpMats[0];
  67012. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  67013. var rotMatInv = Bone._tmpMats[1];
  67014. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67015. rotMatInv.multiplyToRef(rotMat, rotMat);
  67016. this._rotateWithMatrix(rotMat, space, mesh);
  67017. };
  67018. /**
  67019. * Set the euler rotation of the bone in local of world space.
  67020. * @param rotation The euler rotation that the bone should be set to.
  67021. * @param space The space that the rotation is in.
  67022. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67023. */
  67024. Bone.prototype.setRotation = function (rotation, space, mesh) {
  67025. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67026. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  67027. };
  67028. /**
  67029. * Set the quaternion rotation of the bone in local of world space.
  67030. * @param quat The quaternion rotation that the bone should be set to.
  67031. * @param space The space that the rotation is in.
  67032. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67033. */
  67034. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  67035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67036. var rotMatInv = Bone._tmpMats[0];
  67037. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67038. var rotMat = Bone._tmpMats[1];
  67039. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  67040. rotMatInv.multiplyToRef(rotMat, rotMat);
  67041. this._rotateWithMatrix(rotMat, space, mesh);
  67042. };
  67043. /**
  67044. * Set the rotation matrix of the bone in local of world space.
  67045. * @param rotMat The rotation matrix that the bone should be set to.
  67046. * @param space The space that the rotation is in.
  67047. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67048. */
  67049. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  67050. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67051. var rotMatInv = Bone._tmpMats[0];
  67052. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67053. var rotMat2 = Bone._tmpMats[1];
  67054. rotMat2.copyFrom(rotMat);
  67055. rotMatInv.multiplyToRef(rotMat, rotMat2);
  67056. this._rotateWithMatrix(rotMat2, space, mesh);
  67057. };
  67058. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  67059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67060. var lmat = this.getLocalMatrix();
  67061. var lx = lmat.m[12];
  67062. var ly = lmat.m[13];
  67063. var lz = lmat.m[14];
  67064. var parent = this.getParent();
  67065. var parentScale = Bone._tmpMats[3];
  67066. var parentScaleInv = Bone._tmpMats[4];
  67067. if (parent) {
  67068. if (space == BABYLON.Space.WORLD) {
  67069. if (mesh) {
  67070. parentScale.copyFrom(mesh.getWorldMatrix());
  67071. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  67072. }
  67073. else {
  67074. parentScale.copyFrom(parent.getAbsoluteTransform());
  67075. }
  67076. }
  67077. else {
  67078. parentScale = parent._scaleMatrix;
  67079. }
  67080. parentScaleInv.copyFrom(parentScale);
  67081. parentScaleInv.invert();
  67082. lmat.multiplyToRef(parentScale, lmat);
  67083. lmat.multiplyToRef(rmat, lmat);
  67084. lmat.multiplyToRef(parentScaleInv, lmat);
  67085. }
  67086. else {
  67087. if (space == BABYLON.Space.WORLD && mesh) {
  67088. parentScale.copyFrom(mesh.getWorldMatrix());
  67089. parentScaleInv.copyFrom(parentScale);
  67090. parentScaleInv.invert();
  67091. lmat.multiplyToRef(parentScale, lmat);
  67092. lmat.multiplyToRef(rmat, lmat);
  67093. lmat.multiplyToRef(parentScaleInv, lmat);
  67094. }
  67095. else {
  67096. lmat.multiplyToRef(rmat, lmat);
  67097. }
  67098. }
  67099. lmat.m[12] = lx;
  67100. lmat.m[13] = ly;
  67101. lmat.m[14] = lz;
  67102. this.computeAbsoluteTransforms();
  67103. this.markAsDirty();
  67104. };
  67105. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  67106. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67107. if (space == BABYLON.Space.WORLD) {
  67108. var scaleMatrix = Bone._tmpMats[2];
  67109. scaleMatrix.copyFrom(this._scaleMatrix);
  67110. rotMatInv.copyFrom(this.getAbsoluteTransform());
  67111. if (mesh) {
  67112. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  67113. var meshScale = Bone._tmpMats[3];
  67114. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  67115. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  67116. }
  67117. rotMatInv.invert();
  67118. scaleMatrix.m[0] *= this._scalingDeterminant;
  67119. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  67120. }
  67121. else {
  67122. rotMatInv.copyFrom(this.getLocalMatrix());
  67123. rotMatInv.invert();
  67124. var scaleMatrix = Bone._tmpMats[2];
  67125. scaleMatrix.copyFrom(this._scaleMatrix);
  67126. if (this._parent) {
  67127. var pscaleMatrix = Bone._tmpMats[3];
  67128. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  67129. pscaleMatrix.invert();
  67130. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  67131. }
  67132. else {
  67133. scaleMatrix.m[0] *= this._scalingDeterminant;
  67134. }
  67135. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  67136. }
  67137. };
  67138. /**
  67139. * Get the scale of the bone
  67140. * @returns the scale of the bone
  67141. */
  67142. Bone.prototype.getScale = function () {
  67143. return this._scaleVector.clone();
  67144. };
  67145. /**
  67146. * Copy the scale of the bone to a vector3.
  67147. * @param result The vector3 to copy the scale to
  67148. */
  67149. Bone.prototype.getScaleToRef = function (result) {
  67150. result.copyFrom(this._scaleVector);
  67151. };
  67152. /**
  67153. * Get the position of the bone in local or world space.
  67154. * @param space The space that the returned position is in.
  67155. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67156. * @returns The position of the bone
  67157. */
  67158. Bone.prototype.getPosition = function (space, mesh) {
  67159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67160. if (mesh === void 0) { mesh = null; }
  67161. var pos = BABYLON.Vector3.Zero();
  67162. this.getPositionToRef(space, mesh, pos);
  67163. return pos;
  67164. };
  67165. /**
  67166. * Copy the position of the bone to a vector3 in local or world space.
  67167. * @param space The space that the returned position is in.
  67168. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67169. * @param result The vector3 to copy the position to.
  67170. */
  67171. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  67172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67173. if (space == BABYLON.Space.LOCAL) {
  67174. var lm = this.getLocalMatrix();
  67175. result.x = lm.m[12];
  67176. result.y = lm.m[13];
  67177. result.z = lm.m[14];
  67178. }
  67179. else {
  67180. var wm = null;
  67181. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67182. if (mesh) {
  67183. wm = mesh.getWorldMatrix();
  67184. }
  67185. this._skeleton.computeAbsoluteTransforms();
  67186. var tmat = Bone._tmpMats[0];
  67187. if (mesh && wm) {
  67188. tmat.copyFrom(this.getAbsoluteTransform());
  67189. tmat.multiplyToRef(wm, tmat);
  67190. }
  67191. else {
  67192. tmat = this.getAbsoluteTransform();
  67193. }
  67194. result.x = tmat.m[12];
  67195. result.y = tmat.m[13];
  67196. result.z = tmat.m[14];
  67197. }
  67198. };
  67199. /**
  67200. * Get the absolute position of the bone (world space).
  67201. * @param mesh The mesh that this bone is attached to.
  67202. * @returns The absolute position of the bone
  67203. */
  67204. Bone.prototype.getAbsolutePosition = function (mesh) {
  67205. if (mesh === void 0) { mesh = null; }
  67206. var pos = BABYLON.Vector3.Zero();
  67207. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  67208. return pos;
  67209. };
  67210. /**
  67211. * Copy the absolute position of the bone (world space) to the result param.
  67212. * @param mesh The mesh that this bone is attached to.
  67213. * @param result The vector3 to copy the absolute position to.
  67214. */
  67215. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  67216. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  67217. };
  67218. /**
  67219. * Compute the absolute transforms of this bone and its children.
  67220. */
  67221. Bone.prototype.computeAbsoluteTransforms = function () {
  67222. if (this._parent) {
  67223. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  67224. }
  67225. else {
  67226. this._absoluteTransform.copyFrom(this._localMatrix);
  67227. var poseMatrix = this._skeleton.getPoseMatrix();
  67228. if (poseMatrix) {
  67229. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  67230. }
  67231. }
  67232. var children = this.children;
  67233. var len = children.length;
  67234. for (var i = 0; i < len; i++) {
  67235. children[i].computeAbsoluteTransforms();
  67236. }
  67237. };
  67238. Bone.prototype._syncScaleVector = function () {
  67239. var lm = this.getLocalMatrix();
  67240. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  67241. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  67242. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  67243. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  67244. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  67245. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  67246. this._scaleVector.x = xs * Math.sqrt(xsq);
  67247. this._scaleVector.y = ys * Math.sqrt(ysq);
  67248. this._scaleVector.z = zs * Math.sqrt(zsq);
  67249. if (this._parent) {
  67250. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  67251. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  67252. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  67253. }
  67254. 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);
  67255. };
  67256. /**
  67257. * Get the world direction from an axis that is in the local space of the bone.
  67258. * @param localAxis The local direction that is used to compute the world direction.
  67259. * @param mesh The mesh that this bone is attached to.
  67260. * @returns The world direction
  67261. */
  67262. Bone.prototype.getDirection = function (localAxis, mesh) {
  67263. if (mesh === void 0) { mesh = null; }
  67264. var result = BABYLON.Vector3.Zero();
  67265. this.getDirectionToRef(localAxis, mesh, result);
  67266. return result;
  67267. };
  67268. /**
  67269. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  67270. * @param localAxis The local direction that is used to compute the world direction.
  67271. * @param mesh The mesh that this bone is attached to.
  67272. * @param result The vector3 that the world direction will be copied to.
  67273. */
  67274. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  67275. if (mesh === void 0) { mesh = null; }
  67276. var wm = null;
  67277. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67278. if (mesh) {
  67279. wm = mesh.getWorldMatrix();
  67280. }
  67281. this._skeleton.computeAbsoluteTransforms();
  67282. var mat = Bone._tmpMats[0];
  67283. mat.copyFrom(this.getAbsoluteTransform());
  67284. if (mesh && wm) {
  67285. mat.multiplyToRef(wm, mat);
  67286. }
  67287. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  67288. result.normalize();
  67289. };
  67290. /**
  67291. * Get the euler rotation of the bone in local or world space.
  67292. * @param space The space that the rotation should be in.
  67293. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67294. * @returns The euler rotation
  67295. */
  67296. Bone.prototype.getRotation = function (space, mesh) {
  67297. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67298. if (mesh === void 0) { mesh = null; }
  67299. var result = BABYLON.Vector3.Zero();
  67300. this.getRotationToRef(space, mesh, result);
  67301. return result;
  67302. };
  67303. /**
  67304. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  67305. * @param space The space that the rotation should be in.
  67306. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67307. * @param result The vector3 that the rotation should be copied to.
  67308. */
  67309. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  67310. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67311. if (mesh === void 0) { mesh = null; }
  67312. var quat = Bone._tmpQuat;
  67313. this.getRotationQuaternionToRef(space, mesh, quat);
  67314. quat.toEulerAnglesToRef(result);
  67315. };
  67316. /**
  67317. * Get the quaternion rotation of the bone in either local or world space.
  67318. * @param space The space that the rotation should be in.
  67319. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67320. * @returns The quaternion rotation
  67321. */
  67322. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  67323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67324. if (mesh === void 0) { mesh = null; }
  67325. var result = BABYLON.Quaternion.Identity();
  67326. this.getRotationQuaternionToRef(space, mesh, result);
  67327. return result;
  67328. };
  67329. /**
  67330. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  67331. * @param space The space that the rotation should be in.
  67332. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67333. * @param result The quaternion that the rotation should be copied to.
  67334. */
  67335. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  67336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67337. if (mesh === void 0) { mesh = null; }
  67338. if (space == BABYLON.Space.LOCAL) {
  67339. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67340. }
  67341. else {
  67342. var mat = Bone._tmpMats[0];
  67343. var amat = this.getAbsoluteTransform();
  67344. if (mesh) {
  67345. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67346. }
  67347. else {
  67348. mat.copyFrom(amat);
  67349. }
  67350. mat.m[0] *= this._scalingDeterminant;
  67351. mat.m[1] *= this._scalingDeterminant;
  67352. mat.m[2] *= this._scalingDeterminant;
  67353. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67354. }
  67355. };
  67356. /**
  67357. * Get the rotation matrix of the bone in local or world space.
  67358. * @param space The space that the rotation should be in.
  67359. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67360. * @returns The rotation matrix
  67361. */
  67362. Bone.prototype.getRotationMatrix = function (space, mesh) {
  67363. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67364. var result = BABYLON.Matrix.Identity();
  67365. this.getRotationMatrixToRef(space, mesh, result);
  67366. return result;
  67367. };
  67368. /**
  67369. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  67370. * @param space The space that the rotation should be in.
  67371. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67372. * @param result The quaternion that the rotation should be copied to.
  67373. */
  67374. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  67375. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67376. if (space == BABYLON.Space.LOCAL) {
  67377. this.getLocalMatrix().getRotationMatrixToRef(result);
  67378. }
  67379. else {
  67380. var mat = Bone._tmpMats[0];
  67381. var amat = this.getAbsoluteTransform();
  67382. if (mesh) {
  67383. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67384. }
  67385. else {
  67386. mat.copyFrom(amat);
  67387. }
  67388. mat.m[0] *= this._scalingDeterminant;
  67389. mat.m[1] *= this._scalingDeterminant;
  67390. mat.m[2] *= this._scalingDeterminant;
  67391. mat.getRotationMatrixToRef(result);
  67392. }
  67393. };
  67394. /**
  67395. * Get the world position of a point that is in the local space of the bone.
  67396. * @param position The local position
  67397. * @param mesh The mesh that this bone is attached to.
  67398. * @returns The world position
  67399. */
  67400. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  67401. if (mesh === void 0) { mesh = null; }
  67402. var result = BABYLON.Vector3.Zero();
  67403. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  67404. return result;
  67405. };
  67406. /**
  67407. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  67408. * @param position The local position
  67409. * @param mesh The mesh that this bone is attached to.
  67410. * @param result The vector3 that the world position should be copied to.
  67411. */
  67412. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  67413. if (mesh === void 0) { mesh = null; }
  67414. var wm = null;
  67415. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67416. if (mesh) {
  67417. wm = mesh.getWorldMatrix();
  67418. }
  67419. this._skeleton.computeAbsoluteTransforms();
  67420. var tmat = Bone._tmpMats[0];
  67421. if (mesh && wm) {
  67422. tmat.copyFrom(this.getAbsoluteTransform());
  67423. tmat.multiplyToRef(wm, tmat);
  67424. }
  67425. else {
  67426. tmat = this.getAbsoluteTransform();
  67427. }
  67428. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67429. };
  67430. /**
  67431. * Get the local position of a point that is in world space.
  67432. * @param position The world position
  67433. * @param mesh The mesh that this bone is attached to.
  67434. * @returns The local position
  67435. */
  67436. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  67437. if (mesh === void 0) { mesh = null; }
  67438. var result = BABYLON.Vector3.Zero();
  67439. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  67440. return result;
  67441. };
  67442. /**
  67443. * Get the local position of a point that is in world space and copy it to the result param.
  67444. * @param position The world position
  67445. * @param mesh The mesh that this bone is attached to.
  67446. * @param result The vector3 that the local position should be copied to.
  67447. */
  67448. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  67449. if (mesh === void 0) { mesh = null; }
  67450. var wm = null;
  67451. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67452. if (mesh) {
  67453. wm = mesh.getWorldMatrix();
  67454. }
  67455. this._skeleton.computeAbsoluteTransforms();
  67456. var tmat = Bone._tmpMats[0];
  67457. tmat.copyFrom(this.getAbsoluteTransform());
  67458. if (mesh && wm) {
  67459. tmat.multiplyToRef(wm, tmat);
  67460. }
  67461. tmat.invert();
  67462. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67463. };
  67464. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67465. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  67466. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67467. return Bone;
  67468. }(BABYLON.Node));
  67469. BABYLON.Bone = Bone;
  67470. })(BABYLON || (BABYLON = {}));
  67471. //# sourceMappingURL=babylon.bone.js.map
  67472. var BABYLON;
  67473. (function (BABYLON) {
  67474. var BoneIKController = /** @class */ (function () {
  67475. function BoneIKController(mesh, bone, options) {
  67476. this.targetPosition = BABYLON.Vector3.Zero();
  67477. this.poleTargetPosition = BABYLON.Vector3.Zero();
  67478. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  67479. this.poleAngle = 0;
  67480. this.slerpAmount = 1;
  67481. this._bone1Quat = BABYLON.Quaternion.Identity();
  67482. this._bone1Mat = BABYLON.Matrix.Identity();
  67483. this._bone2Ang = Math.PI;
  67484. this._maxAngle = Math.PI;
  67485. this._rightHandedSystem = false;
  67486. this._bendAxis = BABYLON.Vector3.Right();
  67487. this._slerping = false;
  67488. this._adjustRoll = 0;
  67489. this._bone2 = bone;
  67490. this._bone1 = bone.getParent();
  67491. if (!this._bone1) {
  67492. return;
  67493. }
  67494. this.mesh = mesh;
  67495. var bonePos = bone.getPosition();
  67496. if (bone.getAbsoluteTransform().determinant() > 0) {
  67497. this._rightHandedSystem = true;
  67498. this._bendAxis.x = 0;
  67499. this._bendAxis.y = 0;
  67500. this._bendAxis.z = -1;
  67501. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  67502. this._adjustRoll = Math.PI * .5;
  67503. this._bendAxis.z = 1;
  67504. }
  67505. }
  67506. if (this._bone1.length) {
  67507. var boneScale1 = this._bone1.getScale();
  67508. var boneScale2 = this._bone2.getScale();
  67509. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  67510. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  67511. }
  67512. else if (this._bone1.children[0]) {
  67513. mesh.computeWorldMatrix(true);
  67514. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  67515. var pos2 = this._bone2.getAbsolutePosition(mesh);
  67516. var pos3 = this._bone1.getAbsolutePosition(mesh);
  67517. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  67518. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  67519. }
  67520. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  67521. this.maxAngle = Math.PI;
  67522. if (options) {
  67523. if (options.targetMesh) {
  67524. this.targetMesh = options.targetMesh;
  67525. this.targetMesh.computeWorldMatrix(true);
  67526. }
  67527. if (options.poleTargetMesh) {
  67528. this.poleTargetMesh = options.poleTargetMesh;
  67529. this.poleTargetMesh.computeWorldMatrix(true);
  67530. }
  67531. else if (options.poleTargetBone) {
  67532. this.poleTargetBone = options.poleTargetBone;
  67533. }
  67534. else if (this._bone1.getParent()) {
  67535. this.poleTargetBone = this._bone1.getParent();
  67536. }
  67537. if (options.poleTargetLocalOffset) {
  67538. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  67539. }
  67540. if (options.poleAngle) {
  67541. this.poleAngle = options.poleAngle;
  67542. }
  67543. if (options.bendAxis) {
  67544. this._bendAxis.copyFrom(options.bendAxis);
  67545. }
  67546. if (options.maxAngle) {
  67547. this.maxAngle = options.maxAngle;
  67548. }
  67549. if (options.slerpAmount) {
  67550. this.slerpAmount = options.slerpAmount;
  67551. }
  67552. }
  67553. }
  67554. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  67555. get: function () {
  67556. return this._maxAngle;
  67557. },
  67558. set: function (value) {
  67559. this._setMaxAngle(value);
  67560. },
  67561. enumerable: true,
  67562. configurable: true
  67563. });
  67564. BoneIKController.prototype._setMaxAngle = function (ang) {
  67565. if (ang < 0) {
  67566. ang = 0;
  67567. }
  67568. if (ang > Math.PI || ang == undefined) {
  67569. ang = Math.PI;
  67570. }
  67571. this._maxAngle = ang;
  67572. var a = this._bone1Length;
  67573. var b = this._bone2Length;
  67574. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  67575. };
  67576. BoneIKController.prototype.update = function () {
  67577. var bone1 = this._bone1;
  67578. if (!bone1) {
  67579. return;
  67580. }
  67581. var target = this.targetPosition;
  67582. var poleTarget = this.poleTargetPosition;
  67583. var mat1 = BoneIKController._tmpMats[0];
  67584. var mat2 = BoneIKController._tmpMats[1];
  67585. if (this.targetMesh) {
  67586. target.copyFrom(this.targetMesh.getAbsolutePosition());
  67587. }
  67588. if (this.poleTargetBone) {
  67589. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  67590. }
  67591. else if (this.poleTargetMesh) {
  67592. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  67593. }
  67594. var bonePos = BoneIKController._tmpVecs[0];
  67595. var zaxis = BoneIKController._tmpVecs[1];
  67596. var xaxis = BoneIKController._tmpVecs[2];
  67597. var yaxis = BoneIKController._tmpVecs[3];
  67598. var upAxis = BoneIKController._tmpVecs[4];
  67599. var _tmpQuat = BoneIKController._tmpQuat;
  67600. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  67601. poleTarget.subtractToRef(bonePos, upAxis);
  67602. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  67603. upAxis.y = 1;
  67604. }
  67605. else {
  67606. upAxis.normalize();
  67607. }
  67608. target.subtractToRef(bonePos, yaxis);
  67609. yaxis.normalize();
  67610. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  67611. zaxis.normalize();
  67612. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  67613. xaxis.normalize();
  67614. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  67615. var a = this._bone1Length;
  67616. var b = this._bone2Length;
  67617. var c = BABYLON.Vector3.Distance(bonePos, target);
  67618. if (this._maxReach > 0) {
  67619. c = Math.min(this._maxReach, c);
  67620. }
  67621. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  67622. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  67623. if (acosa > 1) {
  67624. acosa = 1;
  67625. }
  67626. if (acosb > 1) {
  67627. acosb = 1;
  67628. }
  67629. if (acosa < -1) {
  67630. acosa = -1;
  67631. }
  67632. if (acosb < -1) {
  67633. acosb = -1;
  67634. }
  67635. var angA = Math.acos(acosa);
  67636. var angB = Math.acos(acosb);
  67637. var angC = -angA - angB;
  67638. if (this._rightHandedSystem) {
  67639. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  67640. mat2.multiplyToRef(mat1, mat1);
  67641. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  67642. mat2.multiplyToRef(mat1, mat1);
  67643. }
  67644. else {
  67645. var _tmpVec = BoneIKController._tmpVecs[5];
  67646. _tmpVec.copyFrom(this._bendAxis);
  67647. _tmpVec.x *= -1;
  67648. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  67649. mat2.multiplyToRef(mat1, mat1);
  67650. }
  67651. if (this.poleAngle) {
  67652. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  67653. mat1.multiplyToRef(mat2, mat1);
  67654. }
  67655. if (this._bone1) {
  67656. if (this.slerpAmount < 1) {
  67657. if (!this._slerping) {
  67658. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  67659. }
  67660. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  67661. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  67662. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  67663. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  67664. this._slerping = true;
  67665. }
  67666. else {
  67667. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  67668. this._bone1Mat.copyFrom(mat1);
  67669. this._slerping = false;
  67670. }
  67671. }
  67672. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  67673. this._bone2Ang = angC;
  67674. };
  67675. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67676. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  67677. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67678. return BoneIKController;
  67679. }());
  67680. BABYLON.BoneIKController = BoneIKController;
  67681. })(BABYLON || (BABYLON = {}));
  67682. //# sourceMappingURL=babylon.boneIKController.js.map
  67683. var BABYLON;
  67684. (function (BABYLON) {
  67685. var BoneLookController = /** @class */ (function () {
  67686. /**
  67687. * Create a BoneLookController
  67688. * @param mesh the mesh that the bone belongs to
  67689. * @param bone the bone that will be looking to the target
  67690. * @param target the target Vector3 to look at
  67691. * @param settings optional settings:
  67692. * - maxYaw: the maximum angle the bone will yaw to
  67693. * - minYaw: the minimum angle the bone will yaw to
  67694. * - maxPitch: the maximum angle the bone will pitch to
  67695. * - minPitch: the minimum angle the bone will yaw to
  67696. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  67697. * - upAxis: the up axis of the coordinate system
  67698. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67699. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  67700. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  67701. * - adjustYaw: used to make an adjustment to the yaw of the bone
  67702. * - adjustPitch: used to make an adjustment to the pitch of the bone
  67703. * - adjustRoll: used to make an adjustment to the roll of the bone
  67704. **/
  67705. function BoneLookController(mesh, bone, target, options) {
  67706. /**
  67707. * The up axis of the coordinate system that is used when the bone is rotated.
  67708. */
  67709. this.upAxis = BABYLON.Vector3.Up();
  67710. /**
  67711. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67712. */
  67713. this.upAxisSpace = BABYLON.Space.LOCAL;
  67714. /**
  67715. * Used to make an adjustment to the yaw of the bone.
  67716. */
  67717. this.adjustYaw = 0;
  67718. /**
  67719. * Used to make an adjustment to the pitch of the bone.
  67720. */
  67721. this.adjustPitch = 0;
  67722. /**
  67723. * Used to make an adjustment to the roll of the bone.
  67724. */
  67725. this.adjustRoll = 0;
  67726. /**
  67727. * 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).
  67728. */
  67729. this.slerpAmount = 1;
  67730. this._boneQuat = BABYLON.Quaternion.Identity();
  67731. this._slerping = false;
  67732. this._firstFrameSkipped = false;
  67733. this._fowardAxis = BABYLON.Vector3.Forward();
  67734. this.mesh = mesh;
  67735. this.bone = bone;
  67736. this.target = target;
  67737. if (options) {
  67738. if (options.adjustYaw) {
  67739. this.adjustYaw = options.adjustYaw;
  67740. }
  67741. if (options.adjustPitch) {
  67742. this.adjustPitch = options.adjustPitch;
  67743. }
  67744. if (options.adjustRoll) {
  67745. this.adjustRoll = options.adjustRoll;
  67746. }
  67747. if (options.maxYaw != null) {
  67748. this.maxYaw = options.maxYaw;
  67749. }
  67750. else {
  67751. this.maxYaw = Math.PI;
  67752. }
  67753. if (options.minYaw != null) {
  67754. this.minYaw = options.minYaw;
  67755. }
  67756. else {
  67757. this.minYaw = -Math.PI;
  67758. }
  67759. if (options.maxPitch != null) {
  67760. this.maxPitch = options.maxPitch;
  67761. }
  67762. else {
  67763. this.maxPitch = Math.PI;
  67764. }
  67765. if (options.minPitch != null) {
  67766. this.minPitch = options.minPitch;
  67767. }
  67768. else {
  67769. this.minPitch = -Math.PI;
  67770. }
  67771. if (options.slerpAmount != null) {
  67772. this.slerpAmount = options.slerpAmount;
  67773. }
  67774. if (options.upAxis != null) {
  67775. this.upAxis = options.upAxis;
  67776. }
  67777. if (options.upAxisSpace != null) {
  67778. this.upAxisSpace = options.upAxisSpace;
  67779. }
  67780. if (options.yawAxis != null || options.pitchAxis != null) {
  67781. var newYawAxis = BABYLON.Axis.Y;
  67782. var newPitchAxis = BABYLON.Axis.X;
  67783. if (options.yawAxis != null) {
  67784. newYawAxis = options.yawAxis.clone();
  67785. newYawAxis.normalize();
  67786. }
  67787. if (options.pitchAxis != null) {
  67788. newPitchAxis = options.pitchAxis.clone();
  67789. newPitchAxis.normalize();
  67790. }
  67791. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  67792. this._transformYawPitch = BABYLON.Matrix.Identity();
  67793. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  67794. this._transformYawPitchInv = this._transformYawPitch.clone();
  67795. this._transformYawPitch.invert();
  67796. }
  67797. }
  67798. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  67799. this.upAxisSpace = BABYLON.Space.LOCAL;
  67800. }
  67801. }
  67802. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  67803. /**
  67804. * Get/set the minimum yaw angle that the bone can look to.
  67805. */
  67806. get: function () {
  67807. return this._minYaw;
  67808. },
  67809. set: function (value) {
  67810. this._minYaw = value;
  67811. this._minYawSin = Math.sin(value);
  67812. this._minYawCos = Math.cos(value);
  67813. if (this._maxYaw != null) {
  67814. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67815. this._yawRange = this._maxYaw - this._minYaw;
  67816. }
  67817. },
  67818. enumerable: true,
  67819. configurable: true
  67820. });
  67821. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  67822. /**
  67823. * Get/set the maximum yaw angle that the bone can look to.
  67824. */
  67825. get: function () {
  67826. return this._maxYaw;
  67827. },
  67828. set: function (value) {
  67829. this._maxYaw = value;
  67830. this._maxYawSin = Math.sin(value);
  67831. this._maxYawCos = Math.cos(value);
  67832. if (this._minYaw != null) {
  67833. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67834. this._yawRange = this._maxYaw - this._minYaw;
  67835. }
  67836. },
  67837. enumerable: true,
  67838. configurable: true
  67839. });
  67840. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  67841. /**
  67842. * Get/set the minimum pitch angle that the bone can look to.
  67843. */
  67844. get: function () {
  67845. return this._minPitch;
  67846. },
  67847. set: function (value) {
  67848. this._minPitch = value;
  67849. this._minPitchTan = Math.tan(value);
  67850. },
  67851. enumerable: true,
  67852. configurable: true
  67853. });
  67854. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  67855. /**
  67856. * Get/set the maximum pitch angle that the bone can look to.
  67857. */
  67858. get: function () {
  67859. return this._maxPitch;
  67860. },
  67861. set: function (value) {
  67862. this._maxPitch = value;
  67863. this._maxPitchTan = Math.tan(value);
  67864. },
  67865. enumerable: true,
  67866. configurable: true
  67867. });
  67868. /**
  67869. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  67870. */
  67871. BoneLookController.prototype.update = function () {
  67872. //skip the first frame when slerping so that the mesh rotation is correct
  67873. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  67874. this._firstFrameSkipped = true;
  67875. return;
  67876. }
  67877. var bone = this.bone;
  67878. var bonePos = BoneLookController._tmpVecs[0];
  67879. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  67880. var target = this.target;
  67881. var _tmpMat1 = BoneLookController._tmpMats[0];
  67882. var _tmpMat2 = BoneLookController._tmpMats[1];
  67883. var mesh = this.mesh;
  67884. var parentBone = bone.getParent();
  67885. var upAxis = BoneLookController._tmpVecs[1];
  67886. upAxis.copyFrom(this.upAxis);
  67887. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  67888. if (this._transformYawPitch) {
  67889. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  67890. }
  67891. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  67892. }
  67893. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  67894. mesh.getDirectionToRef(upAxis, upAxis);
  67895. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  67896. upAxis.normalize();
  67897. }
  67898. }
  67899. var checkYaw = false;
  67900. var checkPitch = false;
  67901. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  67902. checkYaw = true;
  67903. }
  67904. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  67905. checkPitch = true;
  67906. }
  67907. if (checkYaw || checkPitch) {
  67908. var spaceMat = BoneLookController._tmpMats[2];
  67909. var spaceMatInv = BoneLookController._tmpMats[3];
  67910. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  67911. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  67912. }
  67913. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  67914. spaceMat.copyFrom(mesh.getWorldMatrix());
  67915. }
  67916. else {
  67917. var forwardAxis = BoneLookController._tmpVecs[2];
  67918. forwardAxis.copyFrom(this._fowardAxis);
  67919. if (this._transformYawPitch) {
  67920. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  67921. }
  67922. if (parentBone) {
  67923. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  67924. }
  67925. else {
  67926. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  67927. }
  67928. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  67929. rightAxis.normalize();
  67930. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  67931. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  67932. }
  67933. spaceMat.invertToRef(spaceMatInv);
  67934. var xzlen = null;
  67935. if (checkPitch) {
  67936. var localTarget = BoneLookController._tmpVecs[3];
  67937. target.subtractToRef(bonePos, localTarget);
  67938. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67939. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67940. var pitch = Math.atan2(localTarget.y, xzlen);
  67941. var newPitch = pitch;
  67942. if (pitch > this._maxPitch) {
  67943. localTarget.y = this._maxPitchTan * xzlen;
  67944. newPitch = this._maxPitch;
  67945. }
  67946. else if (pitch < this._minPitch) {
  67947. localTarget.y = this._minPitchTan * xzlen;
  67948. newPitch = this._minPitch;
  67949. }
  67950. if (pitch != newPitch) {
  67951. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67952. localTarget.addInPlace(bonePos);
  67953. target = localTarget;
  67954. }
  67955. }
  67956. if (checkYaw) {
  67957. var localTarget = BoneLookController._tmpVecs[4];
  67958. target.subtractToRef(bonePos, localTarget);
  67959. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67960. var yaw = Math.atan2(localTarget.x, localTarget.z);
  67961. var newYaw = yaw;
  67962. if (yaw > this._maxYaw || yaw < this._minYaw) {
  67963. if (xzlen == null) {
  67964. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67965. }
  67966. if (this._yawRange > Math.PI) {
  67967. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  67968. localTarget.z = this._maxYawCos * xzlen;
  67969. localTarget.x = this._maxYawSin * xzlen;
  67970. newYaw = this._maxYaw;
  67971. }
  67972. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  67973. localTarget.z = this._minYawCos * xzlen;
  67974. localTarget.x = this._minYawSin * xzlen;
  67975. newYaw = this._minYaw;
  67976. }
  67977. }
  67978. else {
  67979. if (yaw > this._maxYaw) {
  67980. localTarget.z = this._maxYawCos * xzlen;
  67981. localTarget.x = this._maxYawSin * xzlen;
  67982. newYaw = this._maxYaw;
  67983. }
  67984. else if (yaw < this._minYaw) {
  67985. localTarget.z = this._minYawCos * xzlen;
  67986. localTarget.x = this._minYawSin * xzlen;
  67987. newYaw = this._minYaw;
  67988. }
  67989. }
  67990. }
  67991. if (this._slerping && this._yawRange > Math.PI) {
  67992. //are we going to be crossing into the min/max region?
  67993. var boneFwd = BoneLookController._tmpVecs[8];
  67994. boneFwd.copyFrom(BABYLON.Axis.Z);
  67995. if (this._transformYawPitch) {
  67996. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  67997. }
  67998. var boneRotMat = BoneLookController._tmpMats[4];
  67999. this._boneQuat.toRotationMatrix(boneRotMat);
  68000. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  68001. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  68002. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  68003. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  68004. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  68005. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  68006. if (angBtwTar > angBtwMidYaw) {
  68007. if (xzlen == null) {
  68008. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  68009. }
  68010. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  68011. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  68012. if (angBtwMin < angBtwMax) {
  68013. newYaw = boneYaw + Math.PI * .75;
  68014. localTarget.z = Math.cos(newYaw) * xzlen;
  68015. localTarget.x = Math.sin(newYaw) * xzlen;
  68016. }
  68017. else {
  68018. newYaw = boneYaw - Math.PI * .75;
  68019. localTarget.z = Math.cos(newYaw) * xzlen;
  68020. localTarget.x = Math.sin(newYaw) * xzlen;
  68021. }
  68022. }
  68023. }
  68024. if (yaw != newYaw) {
  68025. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  68026. localTarget.addInPlace(bonePos);
  68027. target = localTarget;
  68028. }
  68029. }
  68030. }
  68031. var zaxis = BoneLookController._tmpVecs[5];
  68032. var xaxis = BoneLookController._tmpVecs[6];
  68033. var yaxis = BoneLookController._tmpVecs[7];
  68034. var _tmpQuat = BoneLookController._tmpQuat;
  68035. target.subtractToRef(bonePos, zaxis);
  68036. zaxis.normalize();
  68037. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  68038. xaxis.normalize();
  68039. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  68040. yaxis.normalize();
  68041. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  68042. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  68043. return;
  68044. }
  68045. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  68046. return;
  68047. }
  68048. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  68049. return;
  68050. }
  68051. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  68052. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  68053. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  68054. }
  68055. if (this.slerpAmount < 1) {
  68056. if (!this._slerping) {
  68057. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  68058. }
  68059. if (this._transformYawPitch) {
  68060. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  68061. }
  68062. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  68063. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  68064. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  68065. this._slerping = true;
  68066. }
  68067. else {
  68068. if (this._transformYawPitch) {
  68069. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  68070. }
  68071. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  68072. this._slerping = false;
  68073. }
  68074. };
  68075. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  68076. var angDiff = ang2 - ang1;
  68077. angDiff %= Math.PI * 2;
  68078. if (angDiff > Math.PI) {
  68079. angDiff -= Math.PI * 2;
  68080. }
  68081. else if (angDiff < -Math.PI) {
  68082. angDiff += Math.PI * 2;
  68083. }
  68084. return angDiff;
  68085. };
  68086. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  68087. ang1 %= (2 * Math.PI);
  68088. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  68089. ang2 %= (2 * Math.PI);
  68090. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  68091. var ab = 0;
  68092. if (ang1 < ang2) {
  68093. ab = ang2 - ang1;
  68094. }
  68095. else {
  68096. ab = ang1 - ang2;
  68097. }
  68098. if (ab > Math.PI) {
  68099. ab = Math.PI * 2 - ab;
  68100. }
  68101. return ab;
  68102. };
  68103. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  68104. ang %= (2 * Math.PI);
  68105. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  68106. ang1 %= (2 * Math.PI);
  68107. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  68108. ang2 %= (2 * Math.PI);
  68109. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  68110. if (ang1 < ang2) {
  68111. if (ang > ang1 && ang < ang2) {
  68112. return true;
  68113. }
  68114. }
  68115. else {
  68116. if (ang > ang2 && ang < ang1) {
  68117. return true;
  68118. }
  68119. }
  68120. return false;
  68121. };
  68122. 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()];
  68123. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  68124. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  68125. return BoneLookController;
  68126. }());
  68127. BABYLON.BoneLookController = BoneLookController;
  68128. })(BABYLON || (BABYLON = {}));
  68129. //# sourceMappingURL=babylon.boneLookController.js.map
  68130. var BABYLON;
  68131. (function (BABYLON) {
  68132. var Skeleton = /** @class */ (function () {
  68133. function Skeleton(name, id, scene) {
  68134. this.name = name;
  68135. this.id = id;
  68136. this.bones = new Array();
  68137. this.needInitialSkinMatrix = false;
  68138. this._isDirty = true;
  68139. this._meshesWithPoseMatrix = new Array();
  68140. this._identity = BABYLON.Matrix.Identity();
  68141. this._ranges = {};
  68142. this._lastAbsoluteTransformsUpdateId = -1;
  68143. // Events
  68144. /**
  68145. * An event triggered before computing the skeleton's matrices
  68146. * @type {BABYLON.Observable}
  68147. */
  68148. this.onBeforeComputeObservable = new BABYLON.Observable();
  68149. this.bones = [];
  68150. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68151. scene.skeletons.push(this);
  68152. //make sure it will recalculate the matrix next time prepare is called.
  68153. this._isDirty = true;
  68154. }
  68155. // Members
  68156. Skeleton.prototype.getTransformMatrices = function (mesh) {
  68157. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  68158. return mesh._bonesTransformMatrices;
  68159. }
  68160. if (!this._transformMatrices) {
  68161. this.prepare();
  68162. }
  68163. return this._transformMatrices;
  68164. };
  68165. Skeleton.prototype.getScene = function () {
  68166. return this._scene;
  68167. };
  68168. // Methods
  68169. /**
  68170. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  68171. */
  68172. Skeleton.prototype.toString = function (fullDetails) {
  68173. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  68174. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  68175. if (fullDetails) {
  68176. ret += ", Ranges: {";
  68177. var first = true;
  68178. for (var name_1 in this._ranges) {
  68179. if (first) {
  68180. ret += ", ";
  68181. first = false;
  68182. }
  68183. ret += name_1;
  68184. }
  68185. ret += "}";
  68186. }
  68187. return ret;
  68188. };
  68189. /**
  68190. * Get bone's index searching by name
  68191. * @param {string} name is bone's name to search for
  68192. * @return {number} Indice of the bone. Returns -1 if not found
  68193. */
  68194. Skeleton.prototype.getBoneIndexByName = function (name) {
  68195. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  68196. if (this.bones[boneIndex].name === name) {
  68197. return boneIndex;
  68198. }
  68199. }
  68200. return -1;
  68201. };
  68202. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  68203. // check name not already in use
  68204. if (!this._ranges[name]) {
  68205. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  68206. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68207. if (this.bones[i].animations[0]) {
  68208. this.bones[i].animations[0].createRange(name, from, to);
  68209. }
  68210. }
  68211. }
  68212. };
  68213. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  68214. if (deleteFrames === void 0) { deleteFrames = true; }
  68215. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68216. if (this.bones[i].animations[0]) {
  68217. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  68218. }
  68219. }
  68220. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  68221. };
  68222. Skeleton.prototype.getAnimationRange = function (name) {
  68223. return this._ranges[name];
  68224. };
  68225. /**
  68226. * Returns as an Array, all AnimationRanges defined on this skeleton
  68227. */
  68228. Skeleton.prototype.getAnimationRanges = function () {
  68229. var animationRanges = [];
  68230. var name;
  68231. var i = 0;
  68232. for (name in this._ranges) {
  68233. animationRanges[i] = this._ranges[name];
  68234. i++;
  68235. }
  68236. return animationRanges;
  68237. };
  68238. /**
  68239. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  68240. */
  68241. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  68242. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68243. if (this._ranges[name] || !source.getAnimationRange(name)) {
  68244. return false;
  68245. }
  68246. var ret = true;
  68247. var frameOffset = this._getHighestAnimationFrame() + 1;
  68248. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  68249. var boneDict = {};
  68250. var sourceBones = source.bones;
  68251. var nBones;
  68252. var i;
  68253. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  68254. boneDict[sourceBones[i].name] = sourceBones[i];
  68255. }
  68256. if (this.bones.length !== sourceBones.length) {
  68257. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  68258. ret = false;
  68259. }
  68260. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  68261. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  68262. var boneName = this.bones[i].name;
  68263. var sourceBone = boneDict[boneName];
  68264. if (sourceBone) {
  68265. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  68266. }
  68267. else {
  68268. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  68269. ret = false;
  68270. }
  68271. }
  68272. // do not call createAnimationRange(), since it also is done to bones, which was already done
  68273. var range = source.getAnimationRange(name);
  68274. if (range) {
  68275. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  68276. }
  68277. return ret;
  68278. };
  68279. Skeleton.prototype.returnToRest = function () {
  68280. for (var index = 0; index < this.bones.length; index++) {
  68281. this.bones[index].returnToRest();
  68282. }
  68283. };
  68284. Skeleton.prototype._getHighestAnimationFrame = function () {
  68285. var ret = 0;
  68286. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68287. if (this.bones[i].animations[0]) {
  68288. var highest = this.bones[i].animations[0].getHighestFrame();
  68289. if (ret < highest) {
  68290. ret = highest;
  68291. }
  68292. }
  68293. }
  68294. return ret;
  68295. };
  68296. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  68297. var range = this.getAnimationRange(name);
  68298. if (!range) {
  68299. return null;
  68300. }
  68301. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  68302. };
  68303. Skeleton.prototype._markAsDirty = function () {
  68304. this._isDirty = true;
  68305. };
  68306. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  68307. this._meshesWithPoseMatrix.push(mesh);
  68308. };
  68309. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  68310. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  68311. if (index > -1) {
  68312. this._meshesWithPoseMatrix.splice(index, 1);
  68313. }
  68314. };
  68315. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  68316. this.onBeforeComputeObservable.notifyObservers(this);
  68317. for (var index = 0; index < this.bones.length; index++) {
  68318. var bone = this.bones[index];
  68319. var parentBone = bone.getParent();
  68320. if (parentBone) {
  68321. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  68322. }
  68323. else {
  68324. if (initialSkinMatrix) {
  68325. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  68326. }
  68327. else {
  68328. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  68329. }
  68330. }
  68331. if (bone._index !== -1) {
  68332. var mappedIndex = bone._index === null ? index : bone._index;
  68333. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  68334. }
  68335. }
  68336. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  68337. };
  68338. Skeleton.prototype.prepare = function () {
  68339. if (!this._isDirty) {
  68340. return;
  68341. }
  68342. if (this.needInitialSkinMatrix) {
  68343. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  68344. var mesh = this._meshesWithPoseMatrix[index];
  68345. var poseMatrix = mesh.getPoseMatrix();
  68346. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  68347. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68348. }
  68349. if (this._synchronizedWithMesh !== mesh) {
  68350. this._synchronizedWithMesh = mesh;
  68351. // Prepare bones
  68352. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  68353. var bone = this.bones[boneIndex];
  68354. if (!bone.getParent()) {
  68355. var matrix = bone.getBaseMatrix();
  68356. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  68357. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  68358. }
  68359. }
  68360. }
  68361. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  68362. }
  68363. }
  68364. else {
  68365. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  68366. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68367. }
  68368. this._computeTransformMatrices(this._transformMatrices, null);
  68369. }
  68370. this._isDirty = false;
  68371. this._scene._activeBones.addCount(this.bones.length, false);
  68372. };
  68373. Skeleton.prototype.getAnimatables = function () {
  68374. if (!this._animatables || this._animatables.length !== this.bones.length) {
  68375. this._animatables = [];
  68376. for (var index = 0; index < this.bones.length; index++) {
  68377. this._animatables.push(this.bones[index]);
  68378. }
  68379. }
  68380. return this._animatables;
  68381. };
  68382. Skeleton.prototype.clone = function (name, id) {
  68383. var result = new Skeleton(name, id || name, this._scene);
  68384. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68385. for (var index = 0; index < this.bones.length; index++) {
  68386. var source = this.bones[index];
  68387. var parentBone = null;
  68388. var parent_1 = source.getParent();
  68389. if (parent_1) {
  68390. var parentIndex = this.bones.indexOf(parent_1);
  68391. parentBone = result.bones[parentIndex];
  68392. }
  68393. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  68394. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  68395. }
  68396. if (this._ranges) {
  68397. result._ranges = {};
  68398. for (var rangeName in this._ranges) {
  68399. var range = this._ranges[rangeName];
  68400. if (range) {
  68401. result._ranges[rangeName] = range.clone();
  68402. }
  68403. }
  68404. }
  68405. this._isDirty = true;
  68406. return result;
  68407. };
  68408. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  68409. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  68410. this.bones.forEach(function (bone) {
  68411. bone.animations.forEach(function (animation) {
  68412. animation.enableBlending = true;
  68413. animation.blendingSpeed = blendingSpeed;
  68414. });
  68415. });
  68416. };
  68417. Skeleton.prototype.dispose = function () {
  68418. this._meshesWithPoseMatrix = [];
  68419. // Animations
  68420. this.getScene().stopAnimation(this);
  68421. // Remove from scene
  68422. this.getScene().removeSkeleton(this);
  68423. };
  68424. Skeleton.prototype.serialize = function () {
  68425. var serializationObject = {};
  68426. serializationObject.name = this.name;
  68427. serializationObject.id = this.id;
  68428. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  68429. serializationObject.bones = [];
  68430. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68431. for (var index = 0; index < this.bones.length; index++) {
  68432. var bone = this.bones[index];
  68433. var parent_2 = bone.getParent();
  68434. var serializedBone = {
  68435. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  68436. name: bone.name,
  68437. matrix: bone.getBaseMatrix().toArray(),
  68438. rest: bone.getRestPose().toArray()
  68439. };
  68440. serializationObject.bones.push(serializedBone);
  68441. if (bone.length) {
  68442. serializedBone.length = bone.length;
  68443. }
  68444. if (bone.animations && bone.animations.length > 0) {
  68445. serializedBone.animation = bone.animations[0].serialize();
  68446. }
  68447. serializationObject.ranges = [];
  68448. for (var name in this._ranges) {
  68449. var source = this._ranges[name];
  68450. if (!source) {
  68451. continue;
  68452. }
  68453. var range = {};
  68454. range.name = name;
  68455. range.from = source.from;
  68456. range.to = source.to;
  68457. serializationObject.ranges.push(range);
  68458. }
  68459. }
  68460. return serializationObject;
  68461. };
  68462. Skeleton.Parse = function (parsedSkeleton, scene) {
  68463. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  68464. if (parsedSkeleton.dimensionsAtRest) {
  68465. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  68466. }
  68467. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  68468. var index;
  68469. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  68470. var parsedBone = parsedSkeleton.bones[index];
  68471. var parentBone = null;
  68472. if (parsedBone.parentBoneIndex > -1) {
  68473. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  68474. }
  68475. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  68476. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  68477. if (parsedBone.length) {
  68478. bone.length = parsedBone.length;
  68479. }
  68480. if (parsedBone.animation) {
  68481. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  68482. }
  68483. }
  68484. // placed after bones, so createAnimationRange can cascade down
  68485. if (parsedSkeleton.ranges) {
  68486. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  68487. var data = parsedSkeleton.ranges[index];
  68488. skeleton.createAnimationRange(data.name, data.from, data.to);
  68489. }
  68490. }
  68491. return skeleton;
  68492. };
  68493. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  68494. if (forceUpdate === void 0) { forceUpdate = false; }
  68495. var renderId = this._scene.getRenderId();
  68496. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  68497. this.bones[0].computeAbsoluteTransforms();
  68498. this._lastAbsoluteTransformsUpdateId = renderId;
  68499. }
  68500. };
  68501. Skeleton.prototype.getPoseMatrix = function () {
  68502. var poseMatrix = null;
  68503. if (this._meshesWithPoseMatrix.length > 0) {
  68504. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  68505. }
  68506. return poseMatrix;
  68507. };
  68508. Skeleton.prototype.sortBones = function () {
  68509. var bones = new Array();
  68510. var visited = new Array(this.bones.length);
  68511. for (var index = 0; index < this.bones.length; index++) {
  68512. this._sortBones(index, bones, visited);
  68513. }
  68514. this.bones = bones;
  68515. };
  68516. Skeleton.prototype._sortBones = function (index, bones, visited) {
  68517. if (visited[index]) {
  68518. return;
  68519. }
  68520. visited[index] = true;
  68521. var bone = this.bones[index];
  68522. if (bone._index === undefined) {
  68523. bone._index = index;
  68524. }
  68525. var parentBone = bone.getParent();
  68526. if (parentBone) {
  68527. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  68528. }
  68529. bones.push(bone);
  68530. };
  68531. return Skeleton;
  68532. }());
  68533. BABYLON.Skeleton = Skeleton;
  68534. })(BABYLON || (BABYLON = {}));
  68535. //# sourceMappingURL=babylon.skeleton.js.map
  68536. var BABYLON;
  68537. (function (BABYLON) {
  68538. var SphericalPolynomial = /** @class */ (function () {
  68539. function SphericalPolynomial() {
  68540. this.x = BABYLON.Vector3.Zero();
  68541. this.y = BABYLON.Vector3.Zero();
  68542. this.z = BABYLON.Vector3.Zero();
  68543. this.xx = BABYLON.Vector3.Zero();
  68544. this.yy = BABYLON.Vector3.Zero();
  68545. this.zz = BABYLON.Vector3.Zero();
  68546. this.xy = BABYLON.Vector3.Zero();
  68547. this.yz = BABYLON.Vector3.Zero();
  68548. this.zx = BABYLON.Vector3.Zero();
  68549. }
  68550. SphericalPolynomial.prototype.addAmbient = function (color) {
  68551. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68552. this.xx = this.xx.add(colorVector);
  68553. this.yy = this.yy.add(colorVector);
  68554. this.zz = this.zz.add(colorVector);
  68555. };
  68556. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  68557. var result = new SphericalPolynomial();
  68558. result.x = harmonics.L11.scale(1.02333);
  68559. result.y = harmonics.L1_1.scale(1.02333);
  68560. result.z = harmonics.L10.scale(1.02333);
  68561. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  68562. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  68563. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  68564. result.yz = harmonics.L2_1.scale(0.858086);
  68565. result.zx = harmonics.L21.scale(0.858086);
  68566. result.xy = harmonics.L2_2.scale(0.858086);
  68567. result.scale(1.0 / Math.PI);
  68568. return result;
  68569. };
  68570. SphericalPolynomial.prototype.scale = function (scale) {
  68571. this.x = this.x.scale(scale);
  68572. this.y = this.y.scale(scale);
  68573. this.z = this.z.scale(scale);
  68574. this.xx = this.xx.scale(scale);
  68575. this.yy = this.yy.scale(scale);
  68576. this.zz = this.zz.scale(scale);
  68577. this.yz = this.yz.scale(scale);
  68578. this.zx = this.zx.scale(scale);
  68579. this.xy = this.xy.scale(scale);
  68580. };
  68581. return SphericalPolynomial;
  68582. }());
  68583. BABYLON.SphericalPolynomial = SphericalPolynomial;
  68584. var SphericalHarmonics = /** @class */ (function () {
  68585. function SphericalHarmonics() {
  68586. this.L00 = BABYLON.Vector3.Zero();
  68587. this.L1_1 = BABYLON.Vector3.Zero();
  68588. this.L10 = BABYLON.Vector3.Zero();
  68589. this.L11 = BABYLON.Vector3.Zero();
  68590. this.L2_2 = BABYLON.Vector3.Zero();
  68591. this.L2_1 = BABYLON.Vector3.Zero();
  68592. this.L20 = BABYLON.Vector3.Zero();
  68593. this.L21 = BABYLON.Vector3.Zero();
  68594. this.L22 = BABYLON.Vector3.Zero();
  68595. }
  68596. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  68597. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68598. var c = colorVector.scale(deltaSolidAngle);
  68599. this.L00 = this.L00.add(c.scale(0.282095));
  68600. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  68601. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  68602. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  68603. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  68604. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  68605. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  68606. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  68607. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  68608. };
  68609. SphericalHarmonics.prototype.scale = function (scale) {
  68610. this.L00 = this.L00.scale(scale);
  68611. this.L1_1 = this.L1_1.scale(scale);
  68612. this.L10 = this.L10.scale(scale);
  68613. this.L11 = this.L11.scale(scale);
  68614. this.L2_2 = this.L2_2.scale(scale);
  68615. this.L2_1 = this.L2_1.scale(scale);
  68616. this.L20 = this.L20.scale(scale);
  68617. this.L21 = this.L21.scale(scale);
  68618. this.L22 = this.L22.scale(scale);
  68619. };
  68620. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  68621. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  68622. //
  68623. // E_lm = A_l * L_lm
  68624. //
  68625. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  68626. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  68627. // the scaling factors are given in equation 9.
  68628. // Constant (Band 0)
  68629. this.L00 = this.L00.scale(3.141593);
  68630. // Linear (Band 1)
  68631. this.L1_1 = this.L1_1.scale(2.094395);
  68632. this.L10 = this.L10.scale(2.094395);
  68633. this.L11 = this.L11.scale(2.094395);
  68634. // Quadratic (Band 2)
  68635. this.L2_2 = this.L2_2.scale(0.785398);
  68636. this.L2_1 = this.L2_1.scale(0.785398);
  68637. this.L20 = this.L20.scale(0.785398);
  68638. this.L21 = this.L21.scale(0.785398);
  68639. this.L22 = this.L22.scale(0.785398);
  68640. };
  68641. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  68642. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  68643. // L = (1/pi) * E * rho
  68644. //
  68645. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  68646. this.scale(1.0 / Math.PI);
  68647. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  68648. // (The pixel shader must apply albedo after texture fetches, etc).
  68649. };
  68650. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  68651. var result = new SphericalHarmonics();
  68652. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  68653. result.L1_1 = polynomial.y.scale(0.977204);
  68654. result.L10 = polynomial.z.scale(0.977204);
  68655. result.L11 = polynomial.x.scale(0.977204);
  68656. result.L2_2 = polynomial.xy.scale(1.16538);
  68657. result.L2_1 = polynomial.yz.scale(1.16538);
  68658. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  68659. result.L21 = polynomial.zx.scale(1.16538);
  68660. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  68661. result.scale(Math.PI);
  68662. return result;
  68663. };
  68664. return SphericalHarmonics;
  68665. }());
  68666. BABYLON.SphericalHarmonics = SphericalHarmonics;
  68667. })(BABYLON || (BABYLON = {}));
  68668. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  68669. var BABYLON;
  68670. (function (BABYLON) {
  68671. var FileFaceOrientation = /** @class */ (function () {
  68672. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  68673. this.name = name;
  68674. this.worldAxisForNormal = worldAxisForNormal;
  68675. this.worldAxisForFileX = worldAxisForFileX;
  68676. this.worldAxisForFileY = worldAxisForFileY;
  68677. }
  68678. return FileFaceOrientation;
  68679. }());
  68680. ;
  68681. /**
  68682. * Helper class dealing with the extraction of spherical polynomial dataArray
  68683. * from a cube map.
  68684. */
  68685. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  68686. function CubeMapToSphericalPolynomialTools() {
  68687. }
  68688. /**
  68689. * Converts a texture to the according Spherical Polynomial data.
  68690. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68691. *
  68692. * @param texture The texture to extract the information from.
  68693. * @return The Spherical Polynomial data.
  68694. */
  68695. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  68696. if (!texture.isCube) {
  68697. // Only supports cube Textures currently.
  68698. return null;
  68699. }
  68700. var size = texture.getSize().width;
  68701. var right = texture.readPixels(0);
  68702. var left = texture.readPixels(1);
  68703. var up;
  68704. var down;
  68705. if (texture.isRenderTarget) {
  68706. up = texture.readPixels(3);
  68707. down = texture.readPixels(2);
  68708. }
  68709. else {
  68710. up = texture.readPixels(2);
  68711. down = texture.readPixels(3);
  68712. }
  68713. var front = texture.readPixels(4);
  68714. var back = texture.readPixels(5);
  68715. var gammaSpace = texture.gammaSpace;
  68716. // Always read as RGBA.
  68717. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  68718. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68719. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68720. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68721. }
  68722. var cubeInfo = {
  68723. size: size,
  68724. right: right,
  68725. left: left,
  68726. up: up,
  68727. down: down,
  68728. front: front,
  68729. back: back,
  68730. format: format,
  68731. type: type,
  68732. gammaSpace: gammaSpace,
  68733. };
  68734. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  68735. };
  68736. /**
  68737. * Converts a cubemap to the according Spherical Polynomial data.
  68738. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68739. *
  68740. * @param cubeInfo The Cube map to extract the information from.
  68741. * @return The Spherical Polynomial data.
  68742. */
  68743. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  68744. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  68745. var totalSolidAngle = 0.0;
  68746. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  68747. var du = 2.0 / cubeInfo.size;
  68748. var dv = du;
  68749. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  68750. var minUV = du * 0.5 - 1.0;
  68751. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68752. var fileFace = this.FileFaces[faceIndex];
  68753. var dataArray = cubeInfo[fileFace.name];
  68754. var v = minUV;
  68755. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  68756. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  68757. // Because SP is still linear, so summation is fine in that basis.
  68758. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  68759. for (var y = 0; y < cubeInfo.size; y++) {
  68760. var u = minUV;
  68761. for (var x = 0; x < cubeInfo.size; x++) {
  68762. // World direction (not normalised)
  68763. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  68764. worldDirection.normalize();
  68765. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  68766. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  68767. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  68768. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  68769. // Handle Integer types.
  68770. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68771. r /= 255;
  68772. g /= 255;
  68773. b /= 255;
  68774. }
  68775. // Handle Gamma space textures.
  68776. if (cubeInfo.gammaSpace) {
  68777. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  68778. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  68779. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  68780. }
  68781. var color = new BABYLON.Color3(r, g, b);
  68782. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  68783. totalSolidAngle += deltaSolidAngle;
  68784. u += du;
  68785. }
  68786. v += dv;
  68787. }
  68788. }
  68789. // Solid angle for entire sphere is 4*pi
  68790. var sphereSolidAngle = 4.0 * Math.PI;
  68791. // Adjust the solid angle to allow for how many faces we processed.
  68792. var facesProcessed = 6.0;
  68793. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  68794. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  68795. // This is needed because the numerical integration over the cube uses a
  68796. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  68797. // and also to compensate for accumulative error due to float precision in the summation.
  68798. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  68799. sphericalHarmonics.scale(correctionFactor);
  68800. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  68801. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  68802. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  68803. };
  68804. CubeMapToSphericalPolynomialTools.FileFaces = [
  68805. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  68806. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  68807. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  68808. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  68809. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  68810. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  68811. ];
  68812. return CubeMapToSphericalPolynomialTools;
  68813. }());
  68814. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  68815. })(BABYLON || (BABYLON = {}));
  68816. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  68817. var BABYLON;
  68818. (function (BABYLON) {
  68819. /**
  68820. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  68821. */
  68822. var PanoramaToCubeMapTools = /** @class */ (function () {
  68823. function PanoramaToCubeMapTools() {
  68824. }
  68825. /**
  68826. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  68827. *
  68828. * @param float32Array The source data.
  68829. * @param inputWidth The width of the input panorama.
  68830. * @param inputhHeight The height of the input panorama.
  68831. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  68832. * @return The cubemap data
  68833. */
  68834. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  68835. if (!float32Array) {
  68836. throw "ConvertPanoramaToCubemap: input cannot be null";
  68837. }
  68838. if (float32Array.length != inputWidth * inputHeight * 3) {
  68839. throw "ConvertPanoramaToCubemap: input size is wrong";
  68840. }
  68841. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  68842. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  68843. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  68844. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  68845. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  68846. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  68847. return {
  68848. front: textureFront,
  68849. back: textureBack,
  68850. left: textureLeft,
  68851. right: textureRight,
  68852. up: textureUp,
  68853. down: textureDown,
  68854. size: size,
  68855. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  68856. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  68857. gammaSpace: false,
  68858. };
  68859. };
  68860. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  68861. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  68862. var textureArray = new Float32Array(buffer);
  68863. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  68864. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  68865. var dy = 1 / texSize;
  68866. var fy = 0;
  68867. for (var y = 0; y < texSize; y++) {
  68868. var xv1 = faceData[0];
  68869. var xv2 = faceData[2];
  68870. for (var x = 0; x < texSize; x++) {
  68871. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  68872. v.normalize();
  68873. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  68874. // 3 channels per pixels
  68875. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  68876. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  68877. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  68878. xv1 = xv1.add(rotDX1);
  68879. xv2 = xv2.add(rotDX2);
  68880. }
  68881. fy += dy;
  68882. }
  68883. return textureArray;
  68884. };
  68885. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  68886. var theta = Math.atan2(vDir.z, vDir.x);
  68887. var phi = Math.acos(vDir.y);
  68888. while (theta < -Math.PI)
  68889. theta += 2 * Math.PI;
  68890. while (theta > Math.PI)
  68891. theta -= 2 * Math.PI;
  68892. var dx = theta / Math.PI;
  68893. var dy = phi / Math.PI;
  68894. // recenter.
  68895. dx = dx * 0.5 + 0.5;
  68896. var px = Math.round(dx * inputWidth);
  68897. if (px < 0)
  68898. px = 0;
  68899. else if (px >= inputWidth)
  68900. px = inputWidth - 1;
  68901. var py = Math.round(dy * inputHeight);
  68902. if (py < 0)
  68903. py = 0;
  68904. else if (py >= inputHeight)
  68905. py = inputHeight - 1;
  68906. var inputY = (inputHeight - py - 1);
  68907. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  68908. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  68909. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  68910. return {
  68911. r: r,
  68912. g: g,
  68913. b: b
  68914. };
  68915. };
  68916. PanoramaToCubeMapTools.FACE_FRONT = [
  68917. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68918. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68919. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68920. new BABYLON.Vector3(1.0, 1.0, -1.0)
  68921. ];
  68922. PanoramaToCubeMapTools.FACE_BACK = [
  68923. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68924. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68925. new BABYLON.Vector3(1.0, 1.0, 1.0),
  68926. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  68927. ];
  68928. PanoramaToCubeMapTools.FACE_RIGHT = [
  68929. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68930. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68931. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68932. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68933. ];
  68934. PanoramaToCubeMapTools.FACE_LEFT = [
  68935. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68936. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68937. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68938. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  68939. ];
  68940. PanoramaToCubeMapTools.FACE_DOWN = [
  68941. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68942. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68943. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68944. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68945. ];
  68946. PanoramaToCubeMapTools.FACE_UP = [
  68947. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68948. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68949. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68950. new BABYLON.Vector3(1.0, -1.0, -1.0)
  68951. ];
  68952. return PanoramaToCubeMapTools;
  68953. }());
  68954. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  68955. })(BABYLON || (BABYLON = {}));
  68956. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  68957. var BABYLON;
  68958. (function (BABYLON) {
  68959. ;
  68960. /**
  68961. * This groups tools to convert HDR texture to native colors array.
  68962. */
  68963. var HDRTools = /** @class */ (function () {
  68964. function HDRTools() {
  68965. }
  68966. HDRTools.Ldexp = function (mantissa, exponent) {
  68967. if (exponent > 1023) {
  68968. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  68969. }
  68970. if (exponent < -1074) {
  68971. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  68972. }
  68973. return mantissa * Math.pow(2, exponent);
  68974. };
  68975. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  68976. if (exponent > 0) {
  68977. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  68978. float32array[index + 0] = red * exponent;
  68979. float32array[index + 1] = green * exponent;
  68980. float32array[index + 2] = blue * exponent;
  68981. }
  68982. else {
  68983. float32array[index + 0] = 0;
  68984. float32array[index + 1] = 0;
  68985. float32array[index + 2] = 0;
  68986. }
  68987. };
  68988. HDRTools.readStringLine = function (uint8array, startIndex) {
  68989. var line = "";
  68990. var character = "";
  68991. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  68992. character = String.fromCharCode(uint8array[i]);
  68993. if (character == "\n") {
  68994. break;
  68995. }
  68996. line += character;
  68997. }
  68998. return line;
  68999. };
  69000. /**
  69001. * Reads header information from an RGBE texture stored in a native array.
  69002. * More information on this format are available here:
  69003. * https://en.wikipedia.org/wiki/RGBE_image_format
  69004. *
  69005. * @param uint8array The binary file stored in native array.
  69006. * @return The header information.
  69007. */
  69008. HDRTools.RGBE_ReadHeader = function (uint8array) {
  69009. var height = 0;
  69010. var width = 0;
  69011. var line = this.readStringLine(uint8array, 0);
  69012. if (line[0] != '#' || line[1] != '?') {
  69013. throw "Bad HDR Format.";
  69014. }
  69015. var endOfHeader = false;
  69016. var findFormat = false;
  69017. var lineIndex = 0;
  69018. do {
  69019. lineIndex += (line.length + 1);
  69020. line = this.readStringLine(uint8array, lineIndex);
  69021. if (line == "FORMAT=32-bit_rle_rgbe") {
  69022. findFormat = true;
  69023. }
  69024. else if (line.length == 0) {
  69025. endOfHeader = true;
  69026. }
  69027. } while (!endOfHeader);
  69028. if (!findFormat) {
  69029. throw "HDR Bad header format, unsupported FORMAT";
  69030. }
  69031. lineIndex += (line.length + 1);
  69032. line = this.readStringLine(uint8array, lineIndex);
  69033. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  69034. var match = sizeRegexp.exec(line);
  69035. // TODO. Support +Y and -X if needed.
  69036. if (!match || match.length < 3) {
  69037. throw "HDR Bad header format, no size";
  69038. }
  69039. width = parseInt(match[2]);
  69040. height = parseInt(match[1]);
  69041. if (width < 8 || width > 0x7fff) {
  69042. throw "HDR Bad header format, unsupported size";
  69043. }
  69044. lineIndex += (line.length + 1);
  69045. return {
  69046. height: height,
  69047. width: width,
  69048. dataPosition: lineIndex
  69049. };
  69050. };
  69051. /**
  69052. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  69053. * This RGBE texture needs to store the information as a panorama.
  69054. *
  69055. * More information on this format are available here:
  69056. * https://en.wikipedia.org/wiki/RGBE_image_format
  69057. *
  69058. * @param buffer The binary file stored in an array buffer.
  69059. * @param size The expected size of the extracted cubemap.
  69060. * @return The Cube Map information.
  69061. */
  69062. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  69063. var uint8array = new Uint8Array(buffer);
  69064. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  69065. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  69066. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  69067. return cubeMapData;
  69068. };
  69069. /**
  69070. * Returns the pixels data extracted from an RGBE texture.
  69071. * This pixels will be stored left to right up to down in the R G B order in one array.
  69072. *
  69073. * More information on this format are available here:
  69074. * https://en.wikipedia.org/wiki/RGBE_image_format
  69075. *
  69076. * @param uint8array The binary file stored in an array buffer.
  69077. * @param hdrInfo The header information of the file.
  69078. * @return The pixels data in RGB right to left up to down order.
  69079. */
  69080. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  69081. // Keep for multi format supports.
  69082. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  69083. };
  69084. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  69085. var num_scanlines = hdrInfo.height;
  69086. var scanline_width = hdrInfo.width;
  69087. var a, b, c, d, count;
  69088. var dataIndex = hdrInfo.dataPosition;
  69089. var index = 0, endIndex = 0, i = 0;
  69090. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  69091. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  69092. // 3 channels of 4 bytes per pixel in float.
  69093. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  69094. var resultArray = new Float32Array(resultBuffer);
  69095. // read in each successive scanline
  69096. while (num_scanlines > 0) {
  69097. a = uint8array[dataIndex++];
  69098. b = uint8array[dataIndex++];
  69099. c = uint8array[dataIndex++];
  69100. d = uint8array[dataIndex++];
  69101. if (a != 2 || b != 2 || (c & 0x80)) {
  69102. // this file is not run length encoded
  69103. throw "HDR Bad header format, not RLE";
  69104. }
  69105. if (((c << 8) | d) != scanline_width) {
  69106. throw "HDR Bad header format, wrong scan line width";
  69107. }
  69108. index = 0;
  69109. // read each of the four channels for the scanline into the buffer
  69110. for (i = 0; i < 4; i++) {
  69111. endIndex = (i + 1) * scanline_width;
  69112. while (index < endIndex) {
  69113. a = uint8array[dataIndex++];
  69114. b = uint8array[dataIndex++];
  69115. if (a > 128) {
  69116. // a run of the same value
  69117. count = a - 128;
  69118. if ((count == 0) || (count > endIndex - index)) {
  69119. throw "HDR Bad Format, bad scanline data (run)";
  69120. }
  69121. while (count-- > 0) {
  69122. scanLineArray[index++] = b;
  69123. }
  69124. }
  69125. else {
  69126. // a non-run
  69127. count = a;
  69128. if ((count == 0) || (count > endIndex - index)) {
  69129. throw "HDR Bad Format, bad scanline data (non-run)";
  69130. }
  69131. scanLineArray[index++] = b;
  69132. if (--count > 0) {
  69133. for (var j = 0; j < count; j++) {
  69134. scanLineArray[index++] = uint8array[dataIndex++];
  69135. }
  69136. }
  69137. }
  69138. }
  69139. }
  69140. // now convert data from buffer into floats
  69141. for (i = 0; i < scanline_width; i++) {
  69142. a = scanLineArray[i];
  69143. b = scanLineArray[i + scanline_width];
  69144. c = scanLineArray[i + 2 * scanline_width];
  69145. d = scanLineArray[i + 3 * scanline_width];
  69146. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  69147. }
  69148. num_scanlines--;
  69149. }
  69150. return resultArray;
  69151. };
  69152. return HDRTools;
  69153. }());
  69154. BABYLON.HDRTools = HDRTools;
  69155. })(BABYLON || (BABYLON = {}));
  69156. //# sourceMappingURL=babylon.hdr.js.map
  69157. var BABYLON;
  69158. (function (BABYLON) {
  69159. /**
  69160. * This represents a texture coming from an HDR input.
  69161. *
  69162. * The only supported format is currently panorama picture stored in RGBE format.
  69163. * Example of such files can be found on HDRLib: http://hdrlib.com/
  69164. */
  69165. var HDRCubeTexture = /** @class */ (function (_super) {
  69166. __extends(HDRCubeTexture, _super);
  69167. /**
  69168. * Instantiates an HDRTexture from the following parameters.
  69169. *
  69170. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  69171. * @param scene The scene the texture will be used in
  69172. * @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.
  69173. * @param noMipmap Forces to not generate the mipmap if true
  69174. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  69175. * @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)
  69176. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  69177. */
  69178. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  69179. if (noMipmap === void 0) { noMipmap = false; }
  69180. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69181. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69182. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69183. if (onLoad === void 0) { onLoad = null; }
  69184. if (onError === void 0) { onError = null; }
  69185. var _this = _super.call(this, scene) || this;
  69186. _this._useInGammaSpace = false;
  69187. _this._generateHarmonics = true;
  69188. _this._isBABYLONPreprocessed = false;
  69189. _this._onLoad = null;
  69190. _this._onError = null;
  69191. /**
  69192. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  69193. */
  69194. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69195. /**
  69196. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  69197. * This is usefull at run time to apply the good shader.
  69198. */
  69199. _this.isPMREM = false;
  69200. _this._isBlocking = true;
  69201. if (!url) {
  69202. return _this;
  69203. }
  69204. _this.name = url;
  69205. _this.url = url;
  69206. _this.hasAlpha = false;
  69207. _this.isCube = true;
  69208. _this._textureMatrix = BABYLON.Matrix.Identity();
  69209. _this._onLoad = onLoad;
  69210. _this._onError = onError;
  69211. _this.gammaSpace = false;
  69212. var caps = scene.getEngine().getCaps();
  69213. if (size) {
  69214. _this._isBABYLONPreprocessed = false;
  69215. _this._noMipmap = noMipmap;
  69216. _this._size = size;
  69217. _this._useInGammaSpace = useInGammaSpace;
  69218. _this._usePMREMGenerator = usePMREMGenerator &&
  69219. caps.textureLOD &&
  69220. caps.textureFloat &&
  69221. !_this._useInGammaSpace;
  69222. }
  69223. else {
  69224. _this._isBABYLONPreprocessed = true;
  69225. _this._noMipmap = false;
  69226. _this._useInGammaSpace = false;
  69227. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  69228. !_this._useInGammaSpace;
  69229. }
  69230. _this.isPMREM = _this._usePMREMGenerator;
  69231. _this._texture = _this._getFromCache(url, _this._noMipmap);
  69232. if (!_this._texture) {
  69233. if (!scene.useDelayedTextureLoading) {
  69234. _this.loadTexture();
  69235. }
  69236. else {
  69237. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69238. }
  69239. }
  69240. return _this;
  69241. }
  69242. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  69243. /**
  69244. * Gets wether or not the texture is blocking during loading.
  69245. */
  69246. get: function () {
  69247. return this._isBlocking;
  69248. },
  69249. /**
  69250. * Sets wether or not the texture is blocking during loading.
  69251. */
  69252. set: function (value) {
  69253. this._isBlocking = value;
  69254. },
  69255. enumerable: true,
  69256. configurable: true
  69257. });
  69258. /**
  69259. * Occurs when the file is a preprocessed .babylon.hdr file.
  69260. */
  69261. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  69262. var _this = this;
  69263. var mipLevels = 0;
  69264. var floatArrayView = null;
  69265. var scene = this.getScene();
  69266. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  69267. var mips = new Array();
  69268. if (!floatArrayView) {
  69269. return mips;
  69270. }
  69271. var startIndex = 30;
  69272. for (var level = 0; level < mipLevels; level++) {
  69273. mips.push([]);
  69274. // Fill each pixel of the mip level.
  69275. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  69276. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69277. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  69278. mips[level].push(faceData);
  69279. startIndex += faceSize;
  69280. }
  69281. }
  69282. return mips;
  69283. } : null;
  69284. var callback = function (buffer) {
  69285. var scene = _this.getScene();
  69286. if (!scene) {
  69287. return null;
  69288. }
  69289. // Create Native Array Views
  69290. var intArrayView = new Int32Array(buffer);
  69291. floatArrayView = new Float32Array(buffer);
  69292. // Fill header.
  69293. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  69294. _this._size = intArrayView[1]; // CubeMap max mip face size.
  69295. // Update Texture Information.
  69296. if (!_this._texture) {
  69297. return null;
  69298. }
  69299. _this._texture.updateSize(_this._size, _this._size);
  69300. // Fill polynomial information.
  69301. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  69302. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  69303. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  69304. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  69305. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  69306. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  69307. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  69308. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  69309. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  69310. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  69311. _this.sphericalPolynomial = sphericalPolynomial;
  69312. // Fill pixel data.
  69313. mipLevels = intArrayView[29]; // Number of mip levels.
  69314. var startIndex = 30;
  69315. var data = [];
  69316. var faceSize = Math.pow(_this._size, 2) * 3;
  69317. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69318. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  69319. startIndex += faceSize;
  69320. }
  69321. var results = [];
  69322. var byteArray = null;
  69323. // Push each faces.
  69324. for (var k = 0; k < 6; k++) {
  69325. var dataFace = null;
  69326. // To be deprecated.
  69327. if (version === 1) {
  69328. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  69329. dataFace = data[j];
  69330. }
  69331. // If special cases.
  69332. if (!mipmapGenerator && dataFace) {
  69333. if (!scene.getEngine().getCaps().textureFloat) {
  69334. // 3 channels of 1 bytes per pixel in bytes.
  69335. var byteBuffer = new ArrayBuffer(faceSize);
  69336. byteArray = new Uint8Array(byteBuffer);
  69337. }
  69338. for (var i = 0; i < _this._size * _this._size; i++) {
  69339. // Put in gamma space if requested.
  69340. if (_this._useInGammaSpace) {
  69341. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69342. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69343. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69344. }
  69345. // Convert to int texture for fallback.
  69346. if (byteArray) {
  69347. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69348. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69349. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69350. // May use luminance instead if the result is not accurate.
  69351. var max = Math.max(Math.max(r, g), b);
  69352. if (max > 255) {
  69353. var scale = 255 / max;
  69354. r *= scale;
  69355. g *= scale;
  69356. b *= scale;
  69357. }
  69358. byteArray[(i * 3) + 0] = r;
  69359. byteArray[(i * 3) + 1] = g;
  69360. byteArray[(i * 3) + 2] = b;
  69361. }
  69362. }
  69363. }
  69364. // Fill the array accordingly.
  69365. if (byteArray) {
  69366. results.push(byteArray);
  69367. }
  69368. else {
  69369. results.push(dataFace);
  69370. }
  69371. }
  69372. return results;
  69373. };
  69374. if (scene) {
  69375. 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);
  69376. }
  69377. };
  69378. /**
  69379. * Occurs when the file is raw .hdr file.
  69380. */
  69381. HDRCubeTexture.prototype.loadHDRTexture = function () {
  69382. var _this = this;
  69383. var callback = function (buffer) {
  69384. var scene = _this.getScene();
  69385. if (!scene) {
  69386. return null;
  69387. }
  69388. // Extract the raw linear data.
  69389. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  69390. // Generate harmonics if needed.
  69391. if (_this._generateHarmonics) {
  69392. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  69393. _this.sphericalPolynomial = sphericalPolynomial;
  69394. }
  69395. var results = [];
  69396. var byteArray = null;
  69397. // Push each faces.
  69398. for (var j = 0; j < 6; j++) {
  69399. // Create uintarray fallback.
  69400. if (!scene.getEngine().getCaps().textureFloat) {
  69401. // 3 channels of 1 bytes per pixel in bytes.
  69402. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  69403. byteArray = new Uint8Array(byteBuffer);
  69404. }
  69405. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  69406. // If special cases.
  69407. if (_this._useInGammaSpace || byteArray) {
  69408. for (var i = 0; i < _this._size * _this._size; i++) {
  69409. // Put in gamma space if requested.
  69410. if (_this._useInGammaSpace) {
  69411. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69412. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69413. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69414. }
  69415. // Convert to int texture for fallback.
  69416. if (byteArray) {
  69417. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69418. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69419. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69420. // May use luminance instead if the result is not accurate.
  69421. var max = Math.max(Math.max(r, g), b);
  69422. if (max > 255) {
  69423. var scale = 255 / max;
  69424. r *= scale;
  69425. g *= scale;
  69426. b *= scale;
  69427. }
  69428. byteArray[(i * 3) + 0] = r;
  69429. byteArray[(i * 3) + 1] = g;
  69430. byteArray[(i * 3) + 2] = b;
  69431. }
  69432. }
  69433. }
  69434. if (byteArray) {
  69435. results.push(byteArray);
  69436. }
  69437. else {
  69438. results.push(dataFace);
  69439. }
  69440. }
  69441. return results;
  69442. };
  69443. var mipmapGenerator = null;
  69444. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  69445. // if (!this._noMipmap &&
  69446. // this._usePMREMGenerator) {
  69447. // mipmapGenerator = (data: ArrayBufferView[]) => {
  69448. // // Custom setup of the generator matching with the PBR shader values.
  69449. // var generator = new BABYLON.PMREMGenerator(data,
  69450. // this._size,
  69451. // this._size,
  69452. // 0,
  69453. // 3,
  69454. // this.getScene().getEngine().getCaps().textureFloat,
  69455. // 2048,
  69456. // 0.25,
  69457. // false,
  69458. // true);
  69459. // return generator.filterCubeMap();
  69460. // };
  69461. // }
  69462. var scene = this.getScene();
  69463. if (scene) {
  69464. 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);
  69465. }
  69466. };
  69467. /**
  69468. * Starts the loading process of the texture.
  69469. */
  69470. HDRCubeTexture.prototype.loadTexture = function () {
  69471. if (this._isBABYLONPreprocessed) {
  69472. this.loadBabylonTexture();
  69473. }
  69474. else {
  69475. this.loadHDRTexture();
  69476. }
  69477. };
  69478. HDRCubeTexture.prototype.clone = function () {
  69479. var scene = this.getScene();
  69480. if (!scene) {
  69481. return this;
  69482. }
  69483. var size = (this._isBABYLONPreprocessed ? null : this._size);
  69484. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  69485. // Base texture
  69486. newTexture.level = this.level;
  69487. newTexture.wrapU = this.wrapU;
  69488. newTexture.wrapV = this.wrapV;
  69489. newTexture.coordinatesIndex = this.coordinatesIndex;
  69490. newTexture.coordinatesMode = this.coordinatesMode;
  69491. return newTexture;
  69492. };
  69493. // Methods
  69494. HDRCubeTexture.prototype.delayLoad = function () {
  69495. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69496. return;
  69497. }
  69498. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69499. this._texture = this._getFromCache(this.url, this._noMipmap);
  69500. if (!this._texture) {
  69501. this.loadTexture();
  69502. }
  69503. };
  69504. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  69505. return this._textureMatrix;
  69506. };
  69507. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69508. this._textureMatrix = value;
  69509. };
  69510. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69511. var texture = null;
  69512. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  69513. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  69514. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  69515. texture.name = parsedTexture.name;
  69516. texture.hasAlpha = parsedTexture.hasAlpha;
  69517. texture.level = parsedTexture.level;
  69518. texture.coordinatesMode = parsedTexture.coordinatesMode;
  69519. texture.isBlocking = parsedTexture.isBlocking;
  69520. }
  69521. return texture;
  69522. };
  69523. HDRCubeTexture.prototype.serialize = function () {
  69524. if (!this.name) {
  69525. return null;
  69526. }
  69527. var serializationObject = {};
  69528. serializationObject.name = this.name;
  69529. serializationObject.hasAlpha = this.hasAlpha;
  69530. serializationObject.isCube = true;
  69531. serializationObject.level = this.level;
  69532. serializationObject.size = this._size;
  69533. serializationObject.coordinatesMode = this.coordinatesMode;
  69534. serializationObject.useInGammaSpace = this._useInGammaSpace;
  69535. serializationObject.generateHarmonics = this._generateHarmonics;
  69536. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  69537. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  69538. serializationObject.customType = "BABYLON.HDRCubeTexture";
  69539. serializationObject.noMipmap = this._noMipmap;
  69540. serializationObject.isBlocking = this._isBlocking;
  69541. return serializationObject;
  69542. };
  69543. /**
  69544. * Saves as a file the data contained in the texture in a binary format.
  69545. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69546. * as the spherical used in the lighting.
  69547. * @param url The HDR file url.
  69548. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69549. * @param onError Method called if any error happens during download.
  69550. * @return The packed binary data.
  69551. */
  69552. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  69553. if (onError === void 0) { onError = null; }
  69554. var callback = function (buffer) {
  69555. var data = new Blob([buffer], { type: 'application/octet-stream' });
  69556. // Returns a URL you can use as a href.
  69557. var objUrl = window.URL.createObjectURL(data);
  69558. // Simulates a link to it and click to dowload.
  69559. var a = document.createElement("a");
  69560. document.body.appendChild(a);
  69561. a.style.display = "none";
  69562. a.href = objUrl;
  69563. a.download = "envmap.babylon.hdr";
  69564. a.click();
  69565. };
  69566. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  69567. };
  69568. /**
  69569. * Serializes the data contained in the texture in a binary format.
  69570. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69571. * as the spherical used in the lighting.
  69572. * @param url The HDR file url.
  69573. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69574. * @param onError Method called if any error happens during download.
  69575. * @return The packed binary data.
  69576. */
  69577. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  69578. if (onError === void 0) { onError = null; }
  69579. // Needs the url tho create the texture.
  69580. if (!url) {
  69581. return;
  69582. }
  69583. // Check Power of two size.
  69584. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  69585. return;
  69586. }
  69587. // Coming Back in 3.x.
  69588. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  69589. };
  69590. HDRCubeTexture._facesMapping = [
  69591. "right",
  69592. "left",
  69593. "up",
  69594. "down",
  69595. "front",
  69596. "back"
  69597. ];
  69598. return HDRCubeTexture;
  69599. }(BABYLON.BaseTexture));
  69600. BABYLON.HDRCubeTexture = HDRCubeTexture;
  69601. })(BABYLON || (BABYLON = {}));
  69602. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  69603. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  69604. // Huge respect for a such great lib.
  69605. // Earcut license:
  69606. // Copyright (c) 2016, Mapbox
  69607. //
  69608. // Permission to use, copy, modify, and/or distribute this software for any purpose
  69609. // with or without fee is hereby granted, provided that the above copyright notice
  69610. // and this permission notice appear in all copies.
  69611. //
  69612. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  69613. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  69614. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  69615. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  69616. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  69617. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  69618. // THIS SOFTWARE.
  69619. var Earcut;
  69620. (function (Earcut) {
  69621. /**
  69622. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  69623. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  69624. * @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).
  69625. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  69626. */
  69627. function earcut(data, holeIndices, dim) {
  69628. dim = dim || 2;
  69629. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  69630. if (!outerNode)
  69631. return triangles;
  69632. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  69633. if (hasHoles)
  69634. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  69635. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  69636. if (data.length > 80 * dim) {
  69637. minX = maxX = data[0];
  69638. minY = maxY = data[1];
  69639. for (var i = dim; i < outerLen; i += dim) {
  69640. x = data[i];
  69641. y = data[i + 1];
  69642. if (x < minX)
  69643. minX = x;
  69644. if (y < minY)
  69645. minY = y;
  69646. if (x > maxX)
  69647. maxX = x;
  69648. if (y > maxY)
  69649. maxY = y;
  69650. }
  69651. // minX, minY and size are later used to transform coords into integers for z-order calculation
  69652. size = Math.max(maxX - minX, maxY - minY);
  69653. }
  69654. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  69655. return triangles;
  69656. }
  69657. Earcut.earcut = earcut;
  69658. var Node = /** @class */ (function () {
  69659. function Node(i, x, y) {
  69660. this.i = i;
  69661. this.x = x;
  69662. this.y = y;
  69663. this.prev = null;
  69664. this.next = null;
  69665. this.z = null;
  69666. this.prevZ = null;
  69667. this.nextZ = null;
  69668. this.steiner = false;
  69669. }
  69670. return Node;
  69671. }());
  69672. // create a circular doubly linked list from polygon points in the specified winding order
  69673. function linkedList(data, start, end, dim, clockwise) {
  69674. var i, last = null;
  69675. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  69676. for (i = start; i < end; i += dim)
  69677. last = insertNode(i, data[i], data[i + 1], last);
  69678. }
  69679. else {
  69680. for (i = end - dim; i >= start; i -= dim)
  69681. last = insertNode(i, data[i], data[i + 1], last);
  69682. }
  69683. if (last && equals(last, last.next)) {
  69684. removeNode(last);
  69685. last = last.next;
  69686. }
  69687. return last;
  69688. }
  69689. // eliminate colinear or duplicate points
  69690. function filterPoints(start, end) {
  69691. if (!start)
  69692. return start;
  69693. if (!end)
  69694. end = start;
  69695. var p = start, again;
  69696. do {
  69697. again = false;
  69698. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  69699. removeNode(p);
  69700. p = end = p.prev;
  69701. if (p === p.next)
  69702. return undefined;
  69703. again = true;
  69704. }
  69705. else {
  69706. p = p.next;
  69707. }
  69708. } while (again || p !== end);
  69709. return end;
  69710. }
  69711. // main ear slicing loop which triangulates a polygon (given as a linked list)
  69712. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  69713. if (!ear)
  69714. return;
  69715. // interlink polygon nodes in z-order
  69716. if (!pass && size)
  69717. indexCurve(ear, minX, minY, size);
  69718. var stop = ear, prev, next;
  69719. // iterate through ears, slicing them one by one
  69720. while (ear.prev !== ear.next) {
  69721. prev = ear.prev;
  69722. next = ear.next;
  69723. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  69724. // cut off the triangle
  69725. triangles.push(prev.i / dim);
  69726. triangles.push(ear.i / dim);
  69727. triangles.push(next.i / dim);
  69728. removeNode(ear);
  69729. // skipping the next vertice leads to less sliver triangles
  69730. ear = next.next;
  69731. stop = next.next;
  69732. continue;
  69733. }
  69734. ear = next;
  69735. // if we looped through the whole remaining polygon and can't find any more ears
  69736. if (ear === stop) {
  69737. // try filtering points and slicing again
  69738. if (!pass) {
  69739. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  69740. // if this didn't work, try curing all small self-intersections locally
  69741. }
  69742. else if (pass === 1) {
  69743. ear = cureLocalIntersections(ear, triangles, dim);
  69744. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  69745. // as a last resort, try splitting the remaining polygon into two
  69746. }
  69747. else if (pass === 2) {
  69748. splitEarcut(ear, triangles, dim, minX, minY, size);
  69749. }
  69750. break;
  69751. }
  69752. }
  69753. }
  69754. // check whether a polygon node forms a valid ear with adjacent nodes
  69755. function isEar(ear) {
  69756. var a = ear.prev, b = ear, c = ear.next;
  69757. if (area(a, b, c) >= 0)
  69758. return false; // reflex, can't be an ear
  69759. // now make sure we don't have other points inside the potential ear
  69760. var p = ear.next.next;
  69761. while (p !== ear.prev) {
  69762. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69763. area(p.prev, p, p.next) >= 0)
  69764. return false;
  69765. p = p.next;
  69766. }
  69767. return true;
  69768. }
  69769. function isEarHashed(ear, minX, minY, size) {
  69770. var a = ear.prev, b = ear, c = ear.next;
  69771. if (area(a, b, c) >= 0)
  69772. return false; // reflex, can't be an ear
  69773. // triangle bbox; min & max are calculated like this for speed
  69774. 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);
  69775. // z-order range for the current triangle bbox;
  69776. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  69777. // first look for points inside the triangle in increasing z-order
  69778. var p = ear.nextZ;
  69779. while (p && p.z <= maxZ) {
  69780. if (p !== ear.prev &&
  69781. p !== ear.next &&
  69782. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69783. area(p.prev, p, p.next) >= 0)
  69784. return false;
  69785. p = p.nextZ;
  69786. }
  69787. // then look for points in decreasing z-order
  69788. p = ear.prevZ;
  69789. while (p && p.z >= minZ) {
  69790. if (p !== ear.prev &&
  69791. p !== ear.next &&
  69792. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69793. area(p.prev, p, p.next) >= 0)
  69794. return false;
  69795. p = p.prevZ;
  69796. }
  69797. return true;
  69798. }
  69799. // go through all polygon nodes and cure small local self-intersections
  69800. function cureLocalIntersections(start, triangles, dim) {
  69801. var p = start;
  69802. do {
  69803. var a = p.prev, b = p.next.next;
  69804. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  69805. triangles.push(a.i / dim);
  69806. triangles.push(p.i / dim);
  69807. triangles.push(b.i / dim);
  69808. // remove two nodes involved
  69809. removeNode(p);
  69810. removeNode(p.next);
  69811. p = start = b;
  69812. }
  69813. p = p.next;
  69814. } while (p !== start);
  69815. return p;
  69816. }
  69817. // try splitting polygon into two and triangulate them independently
  69818. function splitEarcut(start, triangles, dim, minX, minY, size) {
  69819. // look for a valid diagonal that divides the polygon into two
  69820. var a = start;
  69821. do {
  69822. var b = a.next.next;
  69823. while (b !== a.prev) {
  69824. if (a.i !== b.i && isValidDiagonal(a, b)) {
  69825. // split the polygon in two by the diagonal
  69826. var c = splitPolygon(a, b);
  69827. // filter colinear points around the cuts
  69828. a = filterPoints(a, a.next);
  69829. c = filterPoints(c, c.next);
  69830. // run earcut on each half
  69831. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  69832. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  69833. return;
  69834. }
  69835. b = b.next;
  69836. }
  69837. a = a.next;
  69838. } while (a !== start);
  69839. }
  69840. // link every hole into the outer loop, producing a single-ring polygon without holes
  69841. function eliminateHoles(data, holeIndices, outerNode, dim) {
  69842. var queue = [], i, len, start, end, list;
  69843. for (i = 0, len = holeIndices.length; i < len; i++) {
  69844. start = holeIndices[i] * dim;
  69845. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69846. list = linkedList(data, start, end, dim, false);
  69847. if (list === list.next)
  69848. list.steiner = true;
  69849. queue.push(getLeftmost(list));
  69850. }
  69851. queue.sort(compareX);
  69852. // process holes from left to right
  69853. for (i = 0; i < queue.length; i++) {
  69854. eliminateHole(queue[i], outerNode);
  69855. outerNode = filterPoints(outerNode, outerNode.next);
  69856. }
  69857. return outerNode;
  69858. }
  69859. function compareX(a, b) {
  69860. return a.x - b.x;
  69861. }
  69862. // find a bridge between vertices that connects hole with an outer ring and and link it
  69863. function eliminateHole(hole, outerNode) {
  69864. outerNode = findHoleBridge(hole, outerNode);
  69865. if (outerNode) {
  69866. var b = splitPolygon(outerNode, hole);
  69867. filterPoints(b, b.next);
  69868. }
  69869. }
  69870. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  69871. function findHoleBridge(hole, outerNode) {
  69872. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  69873. // find a segment intersected by a ray from the hole's leftmost point to the left;
  69874. // segment's endpoint with lesser x will be potential connection point
  69875. do {
  69876. if (hy <= p.y && hy >= p.next.y) {
  69877. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  69878. if (x <= hx && x > qx) {
  69879. qx = x;
  69880. if (x === hx) {
  69881. if (hy === p.y)
  69882. return p;
  69883. if (hy === p.next.y)
  69884. return p.next;
  69885. }
  69886. m = p.x < p.next.x ? p : p.next;
  69887. }
  69888. }
  69889. p = p.next;
  69890. } while (p !== outerNode);
  69891. if (!m)
  69892. return null;
  69893. if (hx === qx)
  69894. return m.prev; // hole touches outer segment; pick lower endpoint
  69895. // look for points inside the triangle of hole point, segment intersection and endpoint;
  69896. // if there are no points found, we have a valid connection;
  69897. // otherwise choose the point of the minimum angle with the ray as connection point
  69898. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  69899. p = m.next;
  69900. while (p !== stop) {
  69901. if (hx >= p.x &&
  69902. p.x >= mx &&
  69903. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  69904. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  69905. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  69906. m = p;
  69907. tanMin = tan;
  69908. }
  69909. }
  69910. p = p.next;
  69911. }
  69912. return m;
  69913. }
  69914. // interlink polygon nodes in z-order
  69915. function indexCurve(start, minX, minY, size) {
  69916. var p = start;
  69917. do {
  69918. if (p.z === null)
  69919. p.z = zOrder(p.x, p.y, minX, minY, size);
  69920. p.prevZ = p.prev;
  69921. p.nextZ = p.next;
  69922. p = p.next;
  69923. } while (p !== start);
  69924. p.prevZ.nextZ = null;
  69925. p.prevZ = null;
  69926. sortLinked(p);
  69927. }
  69928. // Simon Tatham's linked list merge sort algorithm
  69929. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  69930. function sortLinked(list) {
  69931. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  69932. do {
  69933. p = list;
  69934. list = null;
  69935. tail = null;
  69936. numMerges = 0;
  69937. while (p) {
  69938. numMerges++;
  69939. q = p;
  69940. pSize = 0;
  69941. for (i = 0; i < inSize; i++) {
  69942. pSize++;
  69943. q = q.nextZ;
  69944. if (!q)
  69945. break;
  69946. }
  69947. qSize = inSize;
  69948. while (pSize > 0 || (qSize > 0 && q)) {
  69949. if (pSize === 0) {
  69950. e = q;
  69951. q = q.nextZ;
  69952. qSize--;
  69953. }
  69954. else if (qSize === 0 || !q) {
  69955. e = p;
  69956. p = p.nextZ;
  69957. pSize--;
  69958. }
  69959. else if (p.z <= q.z) {
  69960. e = p;
  69961. p = p.nextZ;
  69962. pSize--;
  69963. }
  69964. else {
  69965. e = q;
  69966. q = q.nextZ;
  69967. qSize--;
  69968. }
  69969. if (tail)
  69970. tail.nextZ = e;
  69971. else
  69972. list = e;
  69973. e.prevZ = tail;
  69974. tail = e;
  69975. }
  69976. p = q;
  69977. }
  69978. tail.nextZ = null;
  69979. inSize *= 2;
  69980. } while (numMerges > 1);
  69981. return list;
  69982. }
  69983. // z-order of a point given coords and size of the data bounding box
  69984. function zOrder(x, y, minX, minY, size) {
  69985. // coords are transformed into non-negative 15-bit integer range
  69986. x = 32767 * (x - minX) / size;
  69987. y = 32767 * (y - minY) / size;
  69988. x = (x | (x << 8)) & 0x00FF00FF;
  69989. x = (x | (x << 4)) & 0x0F0F0F0F;
  69990. x = (x | (x << 2)) & 0x33333333;
  69991. x = (x | (x << 1)) & 0x55555555;
  69992. y = (y | (y << 8)) & 0x00FF00FF;
  69993. y = (y | (y << 4)) & 0x0F0F0F0F;
  69994. y = (y | (y << 2)) & 0x33333333;
  69995. y = (y | (y << 1)) & 0x55555555;
  69996. return x | (y << 1);
  69997. }
  69998. // find the leftmost node of a polygon ring
  69999. function getLeftmost(start) {
  70000. var p = start, leftmost = start;
  70001. do {
  70002. if (p.x < leftmost.x)
  70003. leftmost = p;
  70004. p = p.next;
  70005. } while (p !== start);
  70006. return leftmost;
  70007. }
  70008. // check if a point lies within a convex triangle
  70009. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  70010. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  70011. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  70012. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  70013. }
  70014. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  70015. function isValidDiagonal(a, b) {
  70016. return a.next.i !== b.i &&
  70017. a.prev.i !== b.i &&
  70018. !intersectsPolygon(a, b) &&
  70019. locallyInside(a, b) &&
  70020. locallyInside(b, a) &&
  70021. middleInside(a, b);
  70022. }
  70023. // signed area of a triangle
  70024. function area(p, q, r) {
  70025. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  70026. }
  70027. // check if two points are equal
  70028. function equals(p1, p2) {
  70029. return p1.x === p2.x && p1.y === p2.y;
  70030. }
  70031. // check if two segments intersect
  70032. function intersects(p1, q1, p2, q2) {
  70033. if ((equals(p1, q1) && equals(p2, q2)) ||
  70034. (equals(p1, q2) && equals(p2, q1)))
  70035. return true;
  70036. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  70037. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  70038. }
  70039. // check if a polygon diagonal intersects any polygon segments
  70040. function intersectsPolygon(a, b) {
  70041. var p = a;
  70042. do {
  70043. if (p.i !== a.i &&
  70044. p.next.i !== a.i &&
  70045. p.i !== b.i &&
  70046. p.next.i !== b.i &&
  70047. intersects(p, p.next, a, b))
  70048. return true;
  70049. p = p.next;
  70050. } while (p !== a);
  70051. return false;
  70052. }
  70053. // check if a polygon diagonal is locally inside the polygon
  70054. function locallyInside(a, b) {
  70055. return area(a.prev, a, a.next) < 0
  70056. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  70057. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  70058. }
  70059. // check if the middle point of a polygon diagonal is inside the polygon
  70060. function middleInside(a, b) {
  70061. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  70062. do {
  70063. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  70064. inside = !inside;
  70065. p = p.next;
  70066. } while (p !== a);
  70067. return inside;
  70068. }
  70069. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  70070. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  70071. function splitPolygon(a, b) {
  70072. 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;
  70073. a.next = b;
  70074. b.prev = a;
  70075. a2.next = an;
  70076. an.prev = a2;
  70077. b2.next = a2;
  70078. a2.prev = b2;
  70079. bp.next = b2;
  70080. b2.prev = bp;
  70081. return b2;
  70082. }
  70083. // create a node and optionally link it with previous one (in a circular doubly linked list)
  70084. function insertNode(i, x, y, last) {
  70085. var p = new Node(i, x, y);
  70086. if (!last) {
  70087. p.prev = p;
  70088. p.next = p;
  70089. }
  70090. else {
  70091. p.next = last.next;
  70092. p.prev = last;
  70093. last.next.prev = p;
  70094. last.next = p;
  70095. }
  70096. return p;
  70097. }
  70098. function removeNode(p) {
  70099. p.next.prev = p.prev;
  70100. p.prev.next = p.next;
  70101. if (p.prevZ)
  70102. p.prevZ.nextZ = p.nextZ;
  70103. if (p.nextZ)
  70104. p.nextZ.prevZ = p.prevZ;
  70105. }
  70106. /**
  70107. * return a percentage difference between the polygon area and its triangulation area;
  70108. * used to verify correctness of triangulation
  70109. */
  70110. function deviation(data, holeIndices, dim, triangles) {
  70111. var hasHoles = holeIndices && holeIndices.length;
  70112. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  70113. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  70114. if (hasHoles) {
  70115. for (var i = 0, len = holeIndices.length; i < len; i++) {
  70116. var start = holeIndices[i] * dim;
  70117. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  70118. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  70119. }
  70120. }
  70121. var trianglesArea = 0;
  70122. for (i = 0; i < triangles.length; i += 3) {
  70123. var a = triangles[i] * dim;
  70124. var b = triangles[i + 1] * dim;
  70125. var c = triangles[i + 2] * dim;
  70126. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  70127. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  70128. }
  70129. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  70130. }
  70131. Earcut.deviation = deviation;
  70132. ;
  70133. function signedArea(data, start, end, dim) {
  70134. var sum = 0;
  70135. for (var i = start, j = end - dim; i < end; i += dim) {
  70136. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  70137. j = i;
  70138. }
  70139. return sum;
  70140. }
  70141. /**
  70142. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  70143. */
  70144. function flatten(data) {
  70145. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  70146. for (var i = 0; i < data.length; i++) {
  70147. for (var j = 0; j < data[i].length; j++) {
  70148. for (var d = 0; d < dim; d++)
  70149. result.vertices.push(data[i][j][d]);
  70150. }
  70151. if (i > 0) {
  70152. holeIndex += data[i - 1].length;
  70153. result.holes.push(holeIndex);
  70154. }
  70155. }
  70156. return result;
  70157. }
  70158. Earcut.flatten = flatten;
  70159. ;
  70160. })(Earcut || (Earcut = {}));
  70161. //# sourceMappingURL=babylon.earcut.js.map
  70162. var BABYLON;
  70163. (function (BABYLON) {
  70164. var IndexedVector2 = /** @class */ (function (_super) {
  70165. __extends(IndexedVector2, _super);
  70166. function IndexedVector2(original, index) {
  70167. var _this = _super.call(this, original.x, original.y) || this;
  70168. _this.index = index;
  70169. return _this;
  70170. }
  70171. return IndexedVector2;
  70172. }(BABYLON.Vector2));
  70173. var PolygonPoints = /** @class */ (function () {
  70174. function PolygonPoints() {
  70175. this.elements = new Array();
  70176. }
  70177. PolygonPoints.prototype.add = function (originalPoints) {
  70178. var _this = this;
  70179. var result = new Array();
  70180. originalPoints.forEach(function (point) {
  70181. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  70182. var newPoint = new IndexedVector2(point, _this.elements.length);
  70183. result.push(newPoint);
  70184. _this.elements.push(newPoint);
  70185. }
  70186. });
  70187. return result;
  70188. };
  70189. PolygonPoints.prototype.computeBounds = function () {
  70190. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70191. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70192. this.elements.forEach(function (point) {
  70193. // x
  70194. if (point.x < lmin.x) {
  70195. lmin.x = point.x;
  70196. }
  70197. else if (point.x > lmax.x) {
  70198. lmax.x = point.x;
  70199. }
  70200. // y
  70201. if (point.y < lmin.y) {
  70202. lmin.y = point.y;
  70203. }
  70204. else if (point.y > lmax.y) {
  70205. lmax.y = point.y;
  70206. }
  70207. });
  70208. return {
  70209. min: lmin,
  70210. max: lmax,
  70211. width: lmax.x - lmin.x,
  70212. height: lmax.y - lmin.y
  70213. };
  70214. };
  70215. return PolygonPoints;
  70216. }());
  70217. var Polygon = /** @class */ (function () {
  70218. function Polygon() {
  70219. }
  70220. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  70221. return [
  70222. new BABYLON.Vector2(xmin, ymin),
  70223. new BABYLON.Vector2(xmax, ymin),
  70224. new BABYLON.Vector2(xmax, ymax),
  70225. new BABYLON.Vector2(xmin, ymax)
  70226. ];
  70227. };
  70228. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  70229. if (cx === void 0) { cx = 0; }
  70230. if (cy === void 0) { cy = 0; }
  70231. if (numberOfSides === void 0) { numberOfSides = 32; }
  70232. var result = new Array();
  70233. var angle = 0;
  70234. var increment = (Math.PI * 2) / numberOfSides;
  70235. for (var i = 0; i < numberOfSides; i++) {
  70236. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  70237. angle -= increment;
  70238. }
  70239. return result;
  70240. };
  70241. Polygon.Parse = function (input) {
  70242. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  70243. var i, result = [];
  70244. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  70245. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  70246. }
  70247. return result;
  70248. };
  70249. Polygon.StartingAt = function (x, y) {
  70250. return BABYLON.Path2.StartingAt(x, y);
  70251. };
  70252. return Polygon;
  70253. }());
  70254. BABYLON.Polygon = Polygon;
  70255. var PolygonMeshBuilder = /** @class */ (function () {
  70256. function PolygonMeshBuilder(name, contours, scene) {
  70257. this._points = new PolygonPoints();
  70258. this._outlinepoints = new PolygonPoints();
  70259. this._holes = new Array();
  70260. this._epoints = new Array();
  70261. this._eholes = new Array();
  70262. this._name = name;
  70263. this._scene = scene;
  70264. var points;
  70265. if (contours instanceof BABYLON.Path2) {
  70266. points = contours.getPoints();
  70267. }
  70268. else {
  70269. points = contours;
  70270. }
  70271. this._addToepoint(points);
  70272. this._points.add(points);
  70273. this._outlinepoints.add(points);
  70274. }
  70275. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  70276. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  70277. var p = points_1[_i];
  70278. this._epoints.push(p.x, p.y);
  70279. }
  70280. };
  70281. PolygonMeshBuilder.prototype.addHole = function (hole) {
  70282. this._points.add(hole);
  70283. var holepoints = new PolygonPoints();
  70284. holepoints.add(hole);
  70285. this._holes.push(holepoints);
  70286. this._eholes.push(this._epoints.length / 2);
  70287. this._addToepoint(hole);
  70288. return this;
  70289. };
  70290. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  70291. var _this = this;
  70292. if (updatable === void 0) { updatable = false; }
  70293. if (depth === void 0) { depth = 0; }
  70294. var result = new BABYLON.Mesh(this._name, this._scene);
  70295. var normals = new Array();
  70296. var positions = new Array();
  70297. var uvs = new Array();
  70298. var bounds = this._points.computeBounds();
  70299. this._points.elements.forEach(function (p) {
  70300. normals.push(0, 1.0, 0);
  70301. positions.push(p.x, 0, p.y);
  70302. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  70303. });
  70304. var indices = new Array();
  70305. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  70306. for (var i = 0; i < res.length; i++) {
  70307. indices.push(res[i]);
  70308. }
  70309. if (depth > 0) {
  70310. var positionscount = (positions.length / 3); //get the current pointcount
  70311. this._points.elements.forEach(function (p) {
  70312. normals.push(0, -1.0, 0);
  70313. positions.push(p.x, -depth, p.y);
  70314. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  70315. });
  70316. var totalCount = indices.length;
  70317. for (var i = 0; i < totalCount; i += 3) {
  70318. var i0 = indices[i + 0];
  70319. var i1 = indices[i + 1];
  70320. var i2 = indices[i + 2];
  70321. indices.push(i2 + positionscount);
  70322. indices.push(i1 + positionscount);
  70323. indices.push(i0 + positionscount);
  70324. }
  70325. //Add the sides
  70326. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  70327. this._holes.forEach(function (hole) {
  70328. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  70329. });
  70330. }
  70331. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  70332. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  70333. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  70334. result.setIndices(indices);
  70335. return result;
  70336. };
  70337. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  70338. var StartIndex = positions.length / 3;
  70339. var ulength = 0;
  70340. for (var i = 0; i < points.elements.length; i++) {
  70341. var p = points.elements[i];
  70342. var p1;
  70343. if ((i + 1) > points.elements.length - 1) {
  70344. p1 = points.elements[0];
  70345. }
  70346. else {
  70347. p1 = points.elements[i + 1];
  70348. }
  70349. positions.push(p.x, 0, p.y);
  70350. positions.push(p.x, -depth, p.y);
  70351. positions.push(p1.x, 0, p1.y);
  70352. positions.push(p1.x, -depth, p1.y);
  70353. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  70354. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  70355. var v3 = v2.subtract(v1);
  70356. var v4 = new BABYLON.Vector3(0, 1, 0);
  70357. var vn = BABYLON.Vector3.Cross(v3, v4);
  70358. vn = vn.normalize();
  70359. uvs.push(ulength / bounds.width, 0);
  70360. uvs.push(ulength / bounds.width, 1);
  70361. ulength += v3.length();
  70362. uvs.push((ulength / bounds.width), 0);
  70363. uvs.push((ulength / bounds.width), 1);
  70364. if (!flip) {
  70365. normals.push(-vn.x, -vn.y, -vn.z);
  70366. normals.push(-vn.x, -vn.y, -vn.z);
  70367. normals.push(-vn.x, -vn.y, -vn.z);
  70368. normals.push(-vn.x, -vn.y, -vn.z);
  70369. indices.push(StartIndex);
  70370. indices.push(StartIndex + 1);
  70371. indices.push(StartIndex + 2);
  70372. indices.push(StartIndex + 1);
  70373. indices.push(StartIndex + 3);
  70374. indices.push(StartIndex + 2);
  70375. }
  70376. else {
  70377. normals.push(vn.x, vn.y, vn.z);
  70378. normals.push(vn.x, vn.y, vn.z);
  70379. normals.push(vn.x, vn.y, vn.z);
  70380. normals.push(vn.x, vn.y, vn.z);
  70381. indices.push(StartIndex);
  70382. indices.push(StartIndex + 2);
  70383. indices.push(StartIndex + 1);
  70384. indices.push(StartIndex + 1);
  70385. indices.push(StartIndex + 2);
  70386. indices.push(StartIndex + 3);
  70387. }
  70388. StartIndex += 4;
  70389. }
  70390. ;
  70391. };
  70392. return PolygonMeshBuilder;
  70393. }());
  70394. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  70395. })(BABYLON || (BABYLON = {}));
  70396. //# sourceMappingURL=babylon.polygonMesh.js.map
  70397. var BABYLON;
  70398. (function (BABYLON) {
  70399. // Unique ID when we import meshes from Babylon to CSG
  70400. var currentCSGMeshId = 0;
  70401. // # class Vertex
  70402. // Represents a vertex of a polygon. Use your own vertex class instead of this
  70403. // one to provide additional features like texture coordinates and vertex
  70404. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  70405. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  70406. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  70407. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  70408. // is not used anywhere else.
  70409. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  70410. var Vertex = /** @class */ (function () {
  70411. function Vertex(pos, normal, uv) {
  70412. this.pos = pos;
  70413. this.normal = normal;
  70414. this.uv = uv;
  70415. }
  70416. Vertex.prototype.clone = function () {
  70417. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  70418. };
  70419. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  70420. // orientation of a polygon is flipped.
  70421. Vertex.prototype.flip = function () {
  70422. this.normal = this.normal.scale(-1);
  70423. };
  70424. // Create a new vertex between this vertex and `other` by linearly
  70425. // interpolating all properties using a parameter of `t`. Subclasses should
  70426. // override this to interpolate additional properties.
  70427. Vertex.prototype.interpolate = function (other, t) {
  70428. 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));
  70429. };
  70430. return Vertex;
  70431. }());
  70432. // # class Plane
  70433. // Represents a plane in 3D space.
  70434. var Plane = /** @class */ (function () {
  70435. function Plane(normal, w) {
  70436. this.normal = normal;
  70437. this.w = w;
  70438. }
  70439. Plane.FromPoints = function (a, b, c) {
  70440. var v0 = c.subtract(a);
  70441. var v1 = b.subtract(a);
  70442. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  70443. return null;
  70444. }
  70445. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  70446. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  70447. };
  70448. Plane.prototype.clone = function () {
  70449. return new Plane(this.normal.clone(), this.w);
  70450. };
  70451. Plane.prototype.flip = function () {
  70452. this.normal.scaleInPlace(-1);
  70453. this.w = -this.w;
  70454. };
  70455. // Split `polygon` by this plane if needed, then put the polygon or polygon
  70456. // fragments in the appropriate lists. Coplanar polygons go into either
  70457. // `coplanarFront` or `coplanarBack` depending on their orientation with
  70458. // respect to this plane. Polygons in front or in back of this plane go into
  70459. // either `front` or `back`.
  70460. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  70461. var COPLANAR = 0;
  70462. var FRONT = 1;
  70463. var BACK = 2;
  70464. var SPANNING = 3;
  70465. // Classify each point as well as the entire polygon into one of the above
  70466. // four classes.
  70467. var polygonType = 0;
  70468. var types = [];
  70469. var i;
  70470. var t;
  70471. for (i = 0; i < polygon.vertices.length; i++) {
  70472. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  70473. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  70474. polygonType |= type;
  70475. types.push(type);
  70476. }
  70477. // Put the polygon in the correct list, splitting it when necessary.
  70478. switch (polygonType) {
  70479. case COPLANAR:
  70480. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  70481. break;
  70482. case FRONT:
  70483. front.push(polygon);
  70484. break;
  70485. case BACK:
  70486. back.push(polygon);
  70487. break;
  70488. case SPANNING:
  70489. var f = [], b = [];
  70490. for (i = 0; i < polygon.vertices.length; i++) {
  70491. var j = (i + 1) % polygon.vertices.length;
  70492. var ti = types[i], tj = types[j];
  70493. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  70494. if (ti !== BACK)
  70495. f.push(vi);
  70496. if (ti !== FRONT)
  70497. b.push(ti !== BACK ? vi.clone() : vi);
  70498. if ((ti | tj) === SPANNING) {
  70499. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  70500. var v = vi.interpolate(vj, t);
  70501. f.push(v);
  70502. b.push(v.clone());
  70503. }
  70504. }
  70505. var poly;
  70506. if (f.length >= 3) {
  70507. poly = new Polygon(f, polygon.shared);
  70508. if (poly.plane)
  70509. front.push(poly);
  70510. }
  70511. if (b.length >= 3) {
  70512. poly = new Polygon(b, polygon.shared);
  70513. if (poly.plane)
  70514. back.push(poly);
  70515. }
  70516. break;
  70517. }
  70518. };
  70519. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  70520. // point is on the plane.
  70521. Plane.EPSILON = 1e-5;
  70522. return Plane;
  70523. }());
  70524. // # class Polygon
  70525. // Represents a convex polygon. The vertices used to initialize a polygon must
  70526. // be coplanar and form a convex loop.
  70527. //
  70528. // Each convex polygon has a `shared` property, which is shared between all
  70529. // polygons that are clones of each other or were split from the same polygon.
  70530. // This can be used to define per-polygon properties (such as surface color).
  70531. var Polygon = /** @class */ (function () {
  70532. function Polygon(vertices, shared) {
  70533. this.vertices = vertices;
  70534. this.shared = shared;
  70535. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  70536. }
  70537. Polygon.prototype.clone = function () {
  70538. var vertices = this.vertices.map(function (v) { return v.clone(); });
  70539. return new Polygon(vertices, this.shared);
  70540. };
  70541. Polygon.prototype.flip = function () {
  70542. this.vertices.reverse().map(function (v) { v.flip(); });
  70543. this.plane.flip();
  70544. };
  70545. return Polygon;
  70546. }());
  70547. // # class Node
  70548. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  70549. // by picking a polygon to split along. That polygon (and all other coplanar
  70550. // polygons) are added directly to that node and the other polygons are added to
  70551. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  70552. // no distinction between internal and leaf nodes.
  70553. var Node = /** @class */ (function () {
  70554. function Node(polygons) {
  70555. this.plane = null;
  70556. this.front = null;
  70557. this.back = null;
  70558. this.polygons = new Array();
  70559. if (polygons) {
  70560. this.build(polygons);
  70561. }
  70562. }
  70563. Node.prototype.clone = function () {
  70564. var node = new Node();
  70565. node.plane = this.plane && this.plane.clone();
  70566. node.front = this.front && this.front.clone();
  70567. node.back = this.back && this.back.clone();
  70568. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  70569. return node;
  70570. };
  70571. // Convert solid space to empty space and empty space to solid space.
  70572. Node.prototype.invert = function () {
  70573. for (var i = 0; i < this.polygons.length; i++) {
  70574. this.polygons[i].flip();
  70575. }
  70576. if (this.plane) {
  70577. this.plane.flip();
  70578. }
  70579. if (this.front) {
  70580. this.front.invert();
  70581. }
  70582. if (this.back) {
  70583. this.back.invert();
  70584. }
  70585. var temp = this.front;
  70586. this.front = this.back;
  70587. this.back = temp;
  70588. };
  70589. // Recursively remove all polygons in `polygons` that are inside this BSP
  70590. // tree.
  70591. Node.prototype.clipPolygons = function (polygons) {
  70592. if (!this.plane)
  70593. return polygons.slice();
  70594. var front = new Array(), back = new Array();
  70595. for (var i = 0; i < polygons.length; i++) {
  70596. this.plane.splitPolygon(polygons[i], front, back, front, back);
  70597. }
  70598. if (this.front) {
  70599. front = this.front.clipPolygons(front);
  70600. }
  70601. if (this.back) {
  70602. back = this.back.clipPolygons(back);
  70603. }
  70604. else {
  70605. back = [];
  70606. }
  70607. return front.concat(back);
  70608. };
  70609. // Remove all polygons in this BSP tree that are inside the other BSP tree
  70610. // `bsp`.
  70611. Node.prototype.clipTo = function (bsp) {
  70612. this.polygons = bsp.clipPolygons(this.polygons);
  70613. if (this.front)
  70614. this.front.clipTo(bsp);
  70615. if (this.back)
  70616. this.back.clipTo(bsp);
  70617. };
  70618. // Return a list of all polygons in this BSP tree.
  70619. Node.prototype.allPolygons = function () {
  70620. var polygons = this.polygons.slice();
  70621. if (this.front)
  70622. polygons = polygons.concat(this.front.allPolygons());
  70623. if (this.back)
  70624. polygons = polygons.concat(this.back.allPolygons());
  70625. return polygons;
  70626. };
  70627. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  70628. // new polygons are filtered down to the bottom of the tree and become new
  70629. // nodes there. Each set of polygons is partitioned using the first polygon
  70630. // (no heuristic is used to pick a good split).
  70631. Node.prototype.build = function (polygons) {
  70632. if (!polygons.length)
  70633. return;
  70634. if (!this.plane)
  70635. this.plane = polygons[0].plane.clone();
  70636. var front = new Array(), back = new Array();
  70637. for (var i = 0; i < polygons.length; i++) {
  70638. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  70639. }
  70640. if (front.length) {
  70641. if (!this.front)
  70642. this.front = new Node();
  70643. this.front.build(front);
  70644. }
  70645. if (back.length) {
  70646. if (!this.back)
  70647. this.back = new Node();
  70648. this.back.build(back);
  70649. }
  70650. };
  70651. return Node;
  70652. }());
  70653. var CSG = /** @class */ (function () {
  70654. function CSG() {
  70655. this.polygons = new Array();
  70656. }
  70657. // Convert BABYLON.Mesh to BABYLON.CSG
  70658. CSG.FromMesh = function (mesh) {
  70659. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  70660. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  70661. if (mesh instanceof BABYLON.Mesh) {
  70662. mesh.computeWorldMatrix(true);
  70663. matrix = mesh.getWorldMatrix();
  70664. meshPosition = mesh.position.clone();
  70665. meshRotation = mesh.rotation.clone();
  70666. if (mesh.rotationQuaternion) {
  70667. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  70668. }
  70669. meshScaling = mesh.scaling.clone();
  70670. }
  70671. else {
  70672. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  70673. }
  70674. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70675. var subMeshes = mesh.subMeshes;
  70676. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  70677. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  70678. vertices = [];
  70679. for (var j = 0; j < 3; j++) {
  70680. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  70681. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  70682. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  70683. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  70684. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  70685. vertex = new Vertex(position, normal, uv);
  70686. vertices.push(vertex);
  70687. }
  70688. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  70689. // To handle the case of degenerated triangle
  70690. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  70691. if (polygon.plane)
  70692. polygons.push(polygon);
  70693. }
  70694. }
  70695. var csg = CSG.FromPolygons(polygons);
  70696. csg.matrix = matrix;
  70697. csg.position = meshPosition;
  70698. csg.rotation = meshRotation;
  70699. csg.scaling = meshScaling;
  70700. csg.rotationQuaternion = meshRotationQuaternion;
  70701. currentCSGMeshId++;
  70702. return csg;
  70703. };
  70704. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  70705. CSG.FromPolygons = function (polygons) {
  70706. var csg = new CSG();
  70707. csg.polygons = polygons;
  70708. return csg;
  70709. };
  70710. CSG.prototype.clone = function () {
  70711. var csg = new CSG();
  70712. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  70713. csg.copyTransformAttributes(this);
  70714. return csg;
  70715. };
  70716. CSG.prototype.union = function (csg) {
  70717. var a = new Node(this.clone().polygons);
  70718. var b = new Node(csg.clone().polygons);
  70719. a.clipTo(b);
  70720. b.clipTo(a);
  70721. b.invert();
  70722. b.clipTo(a);
  70723. b.invert();
  70724. a.build(b.allPolygons());
  70725. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70726. };
  70727. CSG.prototype.unionInPlace = function (csg) {
  70728. var a = new Node(this.polygons);
  70729. var b = new Node(csg.polygons);
  70730. a.clipTo(b);
  70731. b.clipTo(a);
  70732. b.invert();
  70733. b.clipTo(a);
  70734. b.invert();
  70735. a.build(b.allPolygons());
  70736. this.polygons = a.allPolygons();
  70737. };
  70738. CSG.prototype.subtract = function (csg) {
  70739. var a = new Node(this.clone().polygons);
  70740. var b = new Node(csg.clone().polygons);
  70741. a.invert();
  70742. a.clipTo(b);
  70743. b.clipTo(a);
  70744. b.invert();
  70745. b.clipTo(a);
  70746. b.invert();
  70747. a.build(b.allPolygons());
  70748. a.invert();
  70749. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70750. };
  70751. CSG.prototype.subtractInPlace = function (csg) {
  70752. var a = new Node(this.polygons);
  70753. var b = new Node(csg.polygons);
  70754. a.invert();
  70755. a.clipTo(b);
  70756. b.clipTo(a);
  70757. b.invert();
  70758. b.clipTo(a);
  70759. b.invert();
  70760. a.build(b.allPolygons());
  70761. a.invert();
  70762. this.polygons = a.allPolygons();
  70763. };
  70764. CSG.prototype.intersect = function (csg) {
  70765. var a = new Node(this.clone().polygons);
  70766. var b = new Node(csg.clone().polygons);
  70767. a.invert();
  70768. b.clipTo(a);
  70769. b.invert();
  70770. a.clipTo(b);
  70771. b.clipTo(a);
  70772. a.build(b.allPolygons());
  70773. a.invert();
  70774. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70775. };
  70776. CSG.prototype.intersectInPlace = function (csg) {
  70777. var a = new Node(this.polygons);
  70778. var b = new Node(csg.polygons);
  70779. a.invert();
  70780. b.clipTo(a);
  70781. b.invert();
  70782. a.clipTo(b);
  70783. b.clipTo(a);
  70784. a.build(b.allPolygons());
  70785. a.invert();
  70786. this.polygons = a.allPolygons();
  70787. };
  70788. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  70789. // not modified.
  70790. CSG.prototype.inverse = function () {
  70791. var csg = this.clone();
  70792. csg.inverseInPlace();
  70793. return csg;
  70794. };
  70795. CSG.prototype.inverseInPlace = function () {
  70796. this.polygons.map(function (p) { p.flip(); });
  70797. };
  70798. // This is used to keep meshes transformations so they can be restored
  70799. // when we build back a Babylon Mesh
  70800. // NB : All CSG operations are performed in world coordinates
  70801. CSG.prototype.copyTransformAttributes = function (csg) {
  70802. this.matrix = csg.matrix;
  70803. this.position = csg.position;
  70804. this.rotation = csg.rotation;
  70805. this.scaling = csg.scaling;
  70806. this.rotationQuaternion = csg.rotationQuaternion;
  70807. return this;
  70808. };
  70809. // Build Raw mesh from CSG
  70810. // Coordinates here are in world space
  70811. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  70812. var matrix = this.matrix.clone();
  70813. matrix.invert();
  70814. 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;
  70815. if (keepSubMeshes) {
  70816. // Sort Polygons, since subMeshes are indices range
  70817. polygons.sort(function (a, b) {
  70818. if (a.shared.meshId === b.shared.meshId) {
  70819. return a.shared.subMeshId - b.shared.subMeshId;
  70820. }
  70821. else {
  70822. return a.shared.meshId - b.shared.meshId;
  70823. }
  70824. });
  70825. }
  70826. for (var i = 0, il = polygons.length; i < il; i++) {
  70827. polygon = polygons[i];
  70828. // Building SubMeshes
  70829. if (!subMesh_dict[polygon.shared.meshId]) {
  70830. subMesh_dict[polygon.shared.meshId] = {};
  70831. }
  70832. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  70833. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  70834. indexStart: +Infinity,
  70835. indexEnd: -Infinity,
  70836. materialIndex: polygon.shared.materialIndex
  70837. };
  70838. }
  70839. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  70840. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  70841. polygonIndices[0] = 0;
  70842. polygonIndices[1] = j - 1;
  70843. polygonIndices[2] = j;
  70844. for (var k = 0; k < 3; k++) {
  70845. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  70846. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  70847. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  70848. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  70849. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  70850. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  70851. // Check if 2 points can be merged
  70852. if (!(typeof vertex_idx !== 'undefined' &&
  70853. normals[vertex_idx * 3] === localNormal.x &&
  70854. normals[vertex_idx * 3 + 1] === localNormal.y &&
  70855. normals[vertex_idx * 3 + 2] === localNormal.z &&
  70856. uvs[vertex_idx * 2] === uv.x &&
  70857. uvs[vertex_idx * 2 + 1] === uv.y)) {
  70858. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  70859. uvs.push(uv.x, uv.y);
  70860. normals.push(normal.x, normal.y, normal.z);
  70861. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  70862. }
  70863. indices.push(vertex_idx);
  70864. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  70865. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  70866. currentIndex++;
  70867. }
  70868. }
  70869. }
  70870. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  70871. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  70872. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  70873. mesh.setIndices(indices, null);
  70874. if (keepSubMeshes) {
  70875. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  70876. var materialIndexOffset = 0, materialMaxIndex;
  70877. mesh.subMeshes = new Array();
  70878. for (var m in subMesh_dict) {
  70879. materialMaxIndex = -1;
  70880. for (var sm in subMesh_dict[m]) {
  70881. subMesh_obj = subMesh_dict[m][sm];
  70882. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  70883. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  70884. }
  70885. materialIndexOffset += ++materialMaxIndex;
  70886. }
  70887. }
  70888. return mesh;
  70889. };
  70890. // Build Mesh from CSG taking material and transforms into account
  70891. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  70892. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  70893. mesh.material = material;
  70894. mesh.position.copyFrom(this.position);
  70895. mesh.rotation.copyFrom(this.rotation);
  70896. if (this.rotationQuaternion) {
  70897. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  70898. }
  70899. mesh.scaling.copyFrom(this.scaling);
  70900. mesh.computeWorldMatrix(true);
  70901. return mesh;
  70902. };
  70903. return CSG;
  70904. }());
  70905. BABYLON.CSG = CSG;
  70906. })(BABYLON || (BABYLON = {}));
  70907. //# sourceMappingURL=babylon.csg.js.map
  70908. var BABYLON;
  70909. (function (BABYLON) {
  70910. var LensFlare = /** @class */ (function () {
  70911. function LensFlare(size, position, color, imgUrl, system) {
  70912. this.size = size;
  70913. this.position = position;
  70914. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  70915. this.color = color || new BABYLON.Color3(1, 1, 1);
  70916. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  70917. this._system = system;
  70918. system.lensFlares.push(this);
  70919. }
  70920. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  70921. return new LensFlare(size, position, color, imgUrl, system);
  70922. };
  70923. LensFlare.prototype.dispose = function () {
  70924. if (this.texture) {
  70925. this.texture.dispose();
  70926. }
  70927. // Remove from scene
  70928. var index = this._system.lensFlares.indexOf(this);
  70929. this._system.lensFlares.splice(index, 1);
  70930. };
  70931. ;
  70932. return LensFlare;
  70933. }());
  70934. BABYLON.LensFlare = LensFlare;
  70935. })(BABYLON || (BABYLON = {}));
  70936. //# sourceMappingURL=babylon.lensFlare.js.map
  70937. var BABYLON;
  70938. (function (BABYLON) {
  70939. var LensFlareSystem = /** @class */ (function () {
  70940. function LensFlareSystem(name, emitter, scene) {
  70941. this.name = name;
  70942. this.lensFlares = new Array();
  70943. this.borderLimit = 300;
  70944. this.viewportBorder = 0;
  70945. this.layerMask = 0x0FFFFFFF;
  70946. this._vertexBuffers = {};
  70947. this._isEnabled = true;
  70948. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70949. this._emitter = emitter;
  70950. this.id = name;
  70951. scene.lensFlareSystems.push(this);
  70952. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  70953. var engine = scene.getEngine();
  70954. // VBO
  70955. var vertices = [];
  70956. vertices.push(1, 1);
  70957. vertices.push(-1, 1);
  70958. vertices.push(-1, -1);
  70959. vertices.push(1, -1);
  70960. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70961. // Indices
  70962. var indices = [];
  70963. indices.push(0);
  70964. indices.push(1);
  70965. indices.push(2);
  70966. indices.push(0);
  70967. indices.push(2);
  70968. indices.push(3);
  70969. this._indexBuffer = engine.createIndexBuffer(indices);
  70970. // Effects
  70971. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  70972. }
  70973. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  70974. get: function () {
  70975. return this._isEnabled;
  70976. },
  70977. set: function (value) {
  70978. this._isEnabled = value;
  70979. },
  70980. enumerable: true,
  70981. configurable: true
  70982. });
  70983. LensFlareSystem.prototype.getScene = function () {
  70984. return this._scene;
  70985. };
  70986. LensFlareSystem.prototype.getEmitter = function () {
  70987. return this._emitter;
  70988. };
  70989. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  70990. this._emitter = newEmitter;
  70991. };
  70992. LensFlareSystem.prototype.getEmitterPosition = function () {
  70993. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  70994. };
  70995. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  70996. var position = this.getEmitterPosition();
  70997. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  70998. this._positionX = position.x;
  70999. this._positionY = position.y;
  71000. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  71001. if (this.viewportBorder > 0) {
  71002. globalViewport.x -= this.viewportBorder;
  71003. globalViewport.y -= this.viewportBorder;
  71004. globalViewport.width += this.viewportBorder * 2;
  71005. globalViewport.height += this.viewportBorder * 2;
  71006. position.x += this.viewportBorder;
  71007. position.y += this.viewportBorder;
  71008. this._positionX += this.viewportBorder;
  71009. this._positionY += this.viewportBorder;
  71010. }
  71011. if (position.z > 0) {
  71012. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  71013. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  71014. return true;
  71015. }
  71016. return true;
  71017. }
  71018. return false;
  71019. };
  71020. LensFlareSystem.prototype._isVisible = function () {
  71021. if (!this._isEnabled || !this._scene.activeCamera) {
  71022. return false;
  71023. }
  71024. var emitterPosition = this.getEmitterPosition();
  71025. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  71026. var distance = direction.length();
  71027. direction.normalize();
  71028. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  71029. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  71030. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  71031. };
  71032. LensFlareSystem.prototype.render = function () {
  71033. if (!this._effect.isReady() || !this._scene.activeCamera)
  71034. return false;
  71035. var engine = this._scene.getEngine();
  71036. var viewport = this._scene.activeCamera.viewport;
  71037. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  71038. // Position
  71039. if (!this.computeEffectivePosition(globalViewport)) {
  71040. return false;
  71041. }
  71042. // Visibility
  71043. if (!this._isVisible()) {
  71044. return false;
  71045. }
  71046. // Intensity
  71047. var awayX;
  71048. var awayY;
  71049. if (this._positionX < this.borderLimit + globalViewport.x) {
  71050. awayX = this.borderLimit + globalViewport.x - this._positionX;
  71051. }
  71052. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  71053. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  71054. }
  71055. else {
  71056. awayX = 0;
  71057. }
  71058. if (this._positionY < this.borderLimit + globalViewport.y) {
  71059. awayY = this.borderLimit + globalViewport.y - this._positionY;
  71060. }
  71061. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  71062. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  71063. }
  71064. else {
  71065. awayY = 0;
  71066. }
  71067. var away = (awayX > awayY) ? awayX : awayY;
  71068. away -= this.viewportBorder;
  71069. if (away > this.borderLimit) {
  71070. away = this.borderLimit;
  71071. }
  71072. var intensity = 1.0 - (away / this.borderLimit);
  71073. if (intensity < 0) {
  71074. return false;
  71075. }
  71076. if (intensity > 1.0) {
  71077. intensity = 1.0;
  71078. }
  71079. if (this.viewportBorder > 0) {
  71080. globalViewport.x += this.viewportBorder;
  71081. globalViewport.y += this.viewportBorder;
  71082. globalViewport.width -= this.viewportBorder * 2;
  71083. globalViewport.height -= this.viewportBorder * 2;
  71084. this._positionX -= this.viewportBorder;
  71085. this._positionY -= this.viewportBorder;
  71086. }
  71087. // Position
  71088. var centerX = globalViewport.x + globalViewport.width / 2;
  71089. var centerY = globalViewport.y + globalViewport.height / 2;
  71090. var distX = centerX - this._positionX;
  71091. var distY = centerY - this._positionY;
  71092. // Effects
  71093. engine.enableEffect(this._effect);
  71094. engine.setState(false);
  71095. engine.setDepthBuffer(false);
  71096. // VBOs
  71097. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71098. // Flares
  71099. for (var index = 0; index < this.lensFlares.length; index++) {
  71100. var flare = this.lensFlares[index];
  71101. engine.setAlphaMode(flare.alphaMode);
  71102. var x = centerX - (distX * flare.position);
  71103. var y = centerY - (distY * flare.position);
  71104. var cw = flare.size;
  71105. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  71106. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  71107. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  71108. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  71109. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  71110. // Texture
  71111. this._effect.setTexture("textureSampler", flare.texture);
  71112. // Color
  71113. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  71114. // Draw order
  71115. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71116. }
  71117. engine.setDepthBuffer(true);
  71118. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71119. return true;
  71120. };
  71121. LensFlareSystem.prototype.dispose = function () {
  71122. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71123. if (vertexBuffer) {
  71124. vertexBuffer.dispose();
  71125. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71126. }
  71127. if (this._indexBuffer) {
  71128. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71129. this._indexBuffer = null;
  71130. }
  71131. while (this.lensFlares.length) {
  71132. this.lensFlares[0].dispose();
  71133. }
  71134. // Remove from scene
  71135. var index = this._scene.lensFlareSystems.indexOf(this);
  71136. this._scene.lensFlareSystems.splice(index, 1);
  71137. };
  71138. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  71139. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  71140. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  71141. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  71142. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  71143. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  71144. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  71145. var parsedFlare = parsedLensFlareSystem.flares[index];
  71146. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  71147. }
  71148. return lensFlareSystem;
  71149. };
  71150. LensFlareSystem.prototype.serialize = function () {
  71151. var serializationObject = {};
  71152. serializationObject.id = this.id;
  71153. serializationObject.name = this.name;
  71154. serializationObject.emitterId = this.getEmitter().id;
  71155. serializationObject.borderLimit = this.borderLimit;
  71156. serializationObject.flares = [];
  71157. for (var index = 0; index < this.lensFlares.length; index++) {
  71158. var flare = this.lensFlares[index];
  71159. serializationObject.flares.push({
  71160. size: flare.size,
  71161. position: flare.position,
  71162. color: flare.color.asArray(),
  71163. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  71164. });
  71165. }
  71166. return serializationObject;
  71167. };
  71168. return LensFlareSystem;
  71169. }());
  71170. BABYLON.LensFlareSystem = LensFlareSystem;
  71171. })(BABYLON || (BABYLON = {}));
  71172. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  71173. var BABYLON;
  71174. (function (BABYLON) {
  71175. /**
  71176. * This is a holder class for the physics joint created by the physics plugin.
  71177. * It holds a set of functions to control the underlying joint.
  71178. */
  71179. var PhysicsJoint = /** @class */ (function () {
  71180. function PhysicsJoint(type, jointData) {
  71181. this.type = type;
  71182. this.jointData = jointData;
  71183. jointData.nativeParams = jointData.nativeParams || {};
  71184. }
  71185. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  71186. get: function () {
  71187. return this._physicsJoint;
  71188. },
  71189. set: function (newJoint) {
  71190. if (this._physicsJoint) {
  71191. //remove from the wolrd
  71192. }
  71193. this._physicsJoint = newJoint;
  71194. },
  71195. enumerable: true,
  71196. configurable: true
  71197. });
  71198. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  71199. set: function (physicsPlugin) {
  71200. this._physicsPlugin = physicsPlugin;
  71201. },
  71202. enumerable: true,
  71203. configurable: true
  71204. });
  71205. /**
  71206. * Execute a function that is physics-plugin specific.
  71207. * @param {Function} func the function that will be executed.
  71208. * It accepts two parameters: the physics world and the physics joint.
  71209. */
  71210. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  71211. func(this._physicsPlugin.world, this._physicsJoint);
  71212. };
  71213. //TODO check if the native joints are the same
  71214. //Joint Types
  71215. PhysicsJoint.DistanceJoint = 0;
  71216. PhysicsJoint.HingeJoint = 1;
  71217. PhysicsJoint.BallAndSocketJoint = 2;
  71218. PhysicsJoint.WheelJoint = 3;
  71219. PhysicsJoint.SliderJoint = 4;
  71220. //OIMO
  71221. PhysicsJoint.PrismaticJoint = 5;
  71222. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  71223. PhysicsJoint.UniversalJoint = 6;
  71224. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  71225. //Cannon
  71226. //Similar to a Ball-Joint. Different in params
  71227. PhysicsJoint.PointToPointJoint = 8;
  71228. //Cannon only at the moment
  71229. PhysicsJoint.SpringJoint = 9;
  71230. PhysicsJoint.LockJoint = 10;
  71231. return PhysicsJoint;
  71232. }());
  71233. BABYLON.PhysicsJoint = PhysicsJoint;
  71234. /**
  71235. * A class representing a physics distance joint.
  71236. */
  71237. var DistanceJoint = /** @class */ (function (_super) {
  71238. __extends(DistanceJoint, _super);
  71239. function DistanceJoint(jointData) {
  71240. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  71241. }
  71242. /**
  71243. * Update the predefined distance.
  71244. */
  71245. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  71246. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  71247. };
  71248. return DistanceJoint;
  71249. }(PhysicsJoint));
  71250. BABYLON.DistanceJoint = DistanceJoint;
  71251. var MotorEnabledJoint = /** @class */ (function (_super) {
  71252. __extends(MotorEnabledJoint, _super);
  71253. function MotorEnabledJoint(type, jointData) {
  71254. return _super.call(this, type, jointData) || this;
  71255. }
  71256. /**
  71257. * Set the motor values.
  71258. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71259. * @param {number} force the force to apply
  71260. * @param {number} maxForce max force for this motor.
  71261. */
  71262. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  71263. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71264. };
  71265. /**
  71266. * Set the motor's limits.
  71267. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71268. */
  71269. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71270. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71271. };
  71272. return MotorEnabledJoint;
  71273. }(PhysicsJoint));
  71274. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  71275. /**
  71276. * This class represents a single hinge physics joint
  71277. */
  71278. var HingeJoint = /** @class */ (function (_super) {
  71279. __extends(HingeJoint, _super);
  71280. function HingeJoint(jointData) {
  71281. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  71282. }
  71283. /**
  71284. * Set the motor values.
  71285. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71286. * @param {number} force the force to apply
  71287. * @param {number} maxForce max force for this motor.
  71288. */
  71289. HingeJoint.prototype.setMotor = function (force, maxForce) {
  71290. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71291. };
  71292. /**
  71293. * Set the motor's limits.
  71294. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71295. */
  71296. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71297. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71298. };
  71299. return HingeJoint;
  71300. }(MotorEnabledJoint));
  71301. BABYLON.HingeJoint = HingeJoint;
  71302. /**
  71303. * This class represents a dual hinge physics joint (same as wheel joint)
  71304. */
  71305. var Hinge2Joint = /** @class */ (function (_super) {
  71306. __extends(Hinge2Joint, _super);
  71307. function Hinge2Joint(jointData) {
  71308. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  71309. }
  71310. /**
  71311. * Set the motor values.
  71312. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71313. * @param {number} force the force to apply
  71314. * @param {number} maxForce max force for this motor.
  71315. * @param {motorIndex} the motor's index, 0 or 1.
  71316. */
  71317. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  71318. if (motorIndex === void 0) { motorIndex = 0; }
  71319. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  71320. };
  71321. /**
  71322. * Set the motor limits.
  71323. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71324. * @param {number} upperLimit the upper limit
  71325. * @param {number} lowerLimit lower limit
  71326. * @param {motorIndex} the motor's index, 0 or 1.
  71327. */
  71328. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  71329. if (motorIndex === void 0) { motorIndex = 0; }
  71330. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  71331. };
  71332. return Hinge2Joint;
  71333. }(MotorEnabledJoint));
  71334. BABYLON.Hinge2Joint = Hinge2Joint;
  71335. })(BABYLON || (BABYLON = {}));
  71336. //# sourceMappingURL=babylon.physicsJoint.js.map
  71337. var BABYLON;
  71338. (function (BABYLON) {
  71339. var PhysicsImpostor = /** @class */ (function () {
  71340. function PhysicsImpostor(object, type, _options, _scene) {
  71341. if (_options === void 0) { _options = { mass: 0 }; }
  71342. var _this = this;
  71343. this.object = object;
  71344. this.type = type;
  71345. this._options = _options;
  71346. this._scene = _scene;
  71347. this._bodyUpdateRequired = false;
  71348. this._onBeforePhysicsStepCallbacks = new Array();
  71349. this._onAfterPhysicsStepCallbacks = new Array();
  71350. this._onPhysicsCollideCallbacks = [];
  71351. this._deltaPosition = BABYLON.Vector3.Zero();
  71352. this._isDisposed = false;
  71353. //temp variables for parent rotation calculations
  71354. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  71355. this._tmpQuat = new BABYLON.Quaternion();
  71356. this._tmpQuat2 = new BABYLON.Quaternion();
  71357. /**
  71358. * this function is executed by the physics engine.
  71359. */
  71360. this.beforeStep = function () {
  71361. if (!_this._physicsEngine) {
  71362. return;
  71363. }
  71364. _this.object.translate(_this._deltaPosition, -1);
  71365. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  71366. _this.object.computeWorldMatrix(false);
  71367. if (_this.object.parent && _this.object.rotationQuaternion) {
  71368. _this.getParentsRotation();
  71369. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  71370. }
  71371. else {
  71372. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  71373. }
  71374. if (!_this._options.disableBidirectionalTransformation) {
  71375. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  71376. }
  71377. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  71378. func(_this);
  71379. });
  71380. };
  71381. /**
  71382. * this function is executed by the physics engine.
  71383. */
  71384. this.afterStep = function () {
  71385. if (!_this._physicsEngine) {
  71386. return;
  71387. }
  71388. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  71389. func(_this);
  71390. });
  71391. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  71392. // object has now its world rotation. needs to be converted to local.
  71393. if (_this.object.parent && _this.object.rotationQuaternion) {
  71394. _this.getParentsRotation();
  71395. _this._tmpQuat.conjugateInPlace();
  71396. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  71397. }
  71398. // take the position set and make it the absolute position of this object.
  71399. _this.object.setAbsolutePosition(_this.object.position);
  71400. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  71401. _this.object.translate(_this._deltaPosition, 1);
  71402. };
  71403. /**
  71404. * Legacy collision detection event support
  71405. */
  71406. this.onCollideEvent = null;
  71407. //event and body object due to cannon's event-based architecture.
  71408. this.onCollide = function (e) {
  71409. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  71410. return;
  71411. }
  71412. if (!_this._physicsEngine) {
  71413. return;
  71414. }
  71415. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  71416. if (otherImpostor) {
  71417. // Legacy collision detection event support
  71418. if (_this.onCollideEvent) {
  71419. _this.onCollideEvent(_this, otherImpostor);
  71420. }
  71421. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  71422. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  71423. }).forEach(function (obj) {
  71424. obj.callback(_this, otherImpostor);
  71425. });
  71426. }
  71427. };
  71428. //sanity check!
  71429. if (!this.object) {
  71430. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  71431. return;
  71432. }
  71433. //legacy support for old syntax.
  71434. if (!this._scene && object.getScene) {
  71435. this._scene = object.getScene();
  71436. }
  71437. if (!this._scene) {
  71438. return;
  71439. }
  71440. this._physicsEngine = this._scene.getPhysicsEngine();
  71441. if (!this._physicsEngine) {
  71442. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  71443. }
  71444. else {
  71445. //set the object's quaternion, if not set
  71446. if (!this.object.rotationQuaternion) {
  71447. if (this.object.rotation) {
  71448. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  71449. }
  71450. else {
  71451. this.object.rotationQuaternion = new BABYLON.Quaternion();
  71452. }
  71453. }
  71454. //default options params
  71455. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  71456. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  71457. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  71458. this._joints = [];
  71459. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  71460. if (!this.object.parent || this._options.ignoreParent) {
  71461. this._init();
  71462. }
  71463. else if (this.object.parent.physicsImpostor) {
  71464. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  71465. }
  71466. }
  71467. }
  71468. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  71469. get: function () {
  71470. return this._isDisposed;
  71471. },
  71472. enumerable: true,
  71473. configurable: true
  71474. });
  71475. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  71476. get: function () {
  71477. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  71478. },
  71479. set: function (value) {
  71480. this.setMass(value);
  71481. },
  71482. enumerable: true,
  71483. configurable: true
  71484. });
  71485. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  71486. get: function () {
  71487. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  71488. },
  71489. set: function (value) {
  71490. if (!this._physicsEngine) {
  71491. return;
  71492. }
  71493. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  71494. },
  71495. enumerable: true,
  71496. configurable: true
  71497. });
  71498. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  71499. get: function () {
  71500. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  71501. },
  71502. set: function (value) {
  71503. if (!this._physicsEngine) {
  71504. return;
  71505. }
  71506. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  71507. },
  71508. enumerable: true,
  71509. configurable: true
  71510. });
  71511. /**
  71512. * This function will completly initialize this impostor.
  71513. * It will create a new body - but only if this mesh has no parent.
  71514. * If it has, this impostor will not be used other than to define the impostor
  71515. * of the child mesh.
  71516. */
  71517. PhysicsImpostor.prototype._init = function () {
  71518. if (!this._physicsEngine) {
  71519. return;
  71520. }
  71521. this._physicsEngine.removeImpostor(this);
  71522. this.physicsBody = null;
  71523. this._parent = this._parent || this._getPhysicsParent();
  71524. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  71525. this._physicsEngine.addImpostor(this);
  71526. }
  71527. };
  71528. PhysicsImpostor.prototype._getPhysicsParent = function () {
  71529. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  71530. var parentMesh = this.object.parent;
  71531. return parentMesh.physicsImpostor;
  71532. }
  71533. return null;
  71534. };
  71535. /**
  71536. * Should a new body be generated.
  71537. */
  71538. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  71539. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  71540. };
  71541. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  71542. this.forceUpdate();
  71543. };
  71544. /**
  71545. * Force a regeneration of this or the parent's impostor's body.
  71546. * Use under cautious - This will remove all joints already implemented.
  71547. */
  71548. PhysicsImpostor.prototype.forceUpdate = function () {
  71549. this._init();
  71550. if (this.parent && !this._options.ignoreParent) {
  71551. this.parent.forceUpdate();
  71552. }
  71553. };
  71554. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  71555. /*public get mesh(): AbstractMesh {
  71556. return this._mesh;
  71557. }*/
  71558. /**
  71559. * Gets the body that holds this impostor. Either its own, or its parent.
  71560. */
  71561. get: function () {
  71562. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  71563. },
  71564. /**
  71565. * Set the physics body. Used mainly by the physics engine/plugin
  71566. */
  71567. set: function (physicsBody) {
  71568. if (this._physicsBody && this._physicsEngine) {
  71569. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  71570. }
  71571. this._physicsBody = physicsBody;
  71572. this.resetUpdateFlags();
  71573. },
  71574. enumerable: true,
  71575. configurable: true
  71576. });
  71577. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  71578. get: function () {
  71579. return !this._options.ignoreParent && this._parent ? this._parent : null;
  71580. },
  71581. set: function (value) {
  71582. this._parent = value;
  71583. },
  71584. enumerable: true,
  71585. configurable: true
  71586. });
  71587. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  71588. this._bodyUpdateRequired = false;
  71589. };
  71590. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  71591. if (this.object.getBoundingInfo) {
  71592. var q = this.object.rotationQuaternion;
  71593. //reset rotation
  71594. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  71595. //calculate the world matrix with no rotation
  71596. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71597. var boundingInfo = this.object.getBoundingInfo();
  71598. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  71599. //bring back the rotation
  71600. this.object.rotationQuaternion = q;
  71601. //calculate the world matrix with the new rotation
  71602. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71603. return size;
  71604. }
  71605. else {
  71606. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  71607. }
  71608. };
  71609. PhysicsImpostor.prototype.getObjectCenter = function () {
  71610. if (this.object.getBoundingInfo) {
  71611. var boundingInfo = this.object.getBoundingInfo();
  71612. return boundingInfo.boundingBox.centerWorld;
  71613. }
  71614. else {
  71615. return this.object.position;
  71616. }
  71617. };
  71618. /**
  71619. * Get a specific parametes from the options parameter.
  71620. */
  71621. PhysicsImpostor.prototype.getParam = function (paramName) {
  71622. return this._options[paramName];
  71623. };
  71624. /**
  71625. * Sets a specific parameter in the options given to the physics plugin
  71626. */
  71627. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  71628. this._options[paramName] = value;
  71629. this._bodyUpdateRequired = true;
  71630. };
  71631. /**
  71632. * Specifically change the body's mass option. Won't recreate the physics body object
  71633. */
  71634. PhysicsImpostor.prototype.setMass = function (mass) {
  71635. if (this.getParam("mass") !== mass) {
  71636. this.setParam("mass", mass);
  71637. }
  71638. if (this._physicsEngine) {
  71639. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  71640. }
  71641. };
  71642. PhysicsImpostor.prototype.getLinearVelocity = function () {
  71643. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  71644. };
  71645. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  71646. if (this._physicsEngine) {
  71647. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  71648. }
  71649. };
  71650. PhysicsImpostor.prototype.getAngularVelocity = function () {
  71651. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  71652. };
  71653. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  71654. if (this._physicsEngine) {
  71655. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  71656. }
  71657. };
  71658. /**
  71659. * Execute a function with the physics plugin native code.
  71660. * Provide a function the will have two variables - the world object and the physics body object.
  71661. */
  71662. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  71663. if (this._physicsEngine) {
  71664. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  71665. }
  71666. };
  71667. /**
  71668. * Register a function that will be executed before the physics world is stepping forward.
  71669. */
  71670. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  71671. this._onBeforePhysicsStepCallbacks.push(func);
  71672. };
  71673. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  71674. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  71675. if (index > -1) {
  71676. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  71677. }
  71678. else {
  71679. BABYLON.Tools.Warn("Function to remove was not found");
  71680. }
  71681. };
  71682. /**
  71683. * Register a function that will be executed after the physics step
  71684. */
  71685. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  71686. this._onAfterPhysicsStepCallbacks.push(func);
  71687. };
  71688. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  71689. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  71690. if (index > -1) {
  71691. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  71692. }
  71693. else {
  71694. BABYLON.Tools.Warn("Function to remove was not found");
  71695. }
  71696. };
  71697. /**
  71698. * register a function that will be executed when this impostor collides against a different body.
  71699. */
  71700. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  71701. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71702. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  71703. };
  71704. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  71705. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71706. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  71707. if (index > -1) {
  71708. this._onPhysicsCollideCallbacks.splice(index, 1);
  71709. }
  71710. else {
  71711. BABYLON.Tools.Warn("Function to remove was not found");
  71712. }
  71713. };
  71714. PhysicsImpostor.prototype.getParentsRotation = function () {
  71715. var parent = this.object.parent;
  71716. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  71717. while (parent) {
  71718. if (parent.rotationQuaternion) {
  71719. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  71720. }
  71721. else {
  71722. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  71723. }
  71724. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  71725. parent = parent.parent;
  71726. }
  71727. return this._tmpQuat;
  71728. };
  71729. /**
  71730. * Apply a force
  71731. */
  71732. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  71733. if (this._physicsEngine) {
  71734. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  71735. }
  71736. return this;
  71737. };
  71738. /**
  71739. * Apply an impulse
  71740. */
  71741. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  71742. if (this._physicsEngine) {
  71743. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  71744. }
  71745. return this;
  71746. };
  71747. /**
  71748. * A help function to create a joint.
  71749. */
  71750. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  71751. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  71752. this.addJoint(otherImpostor, joint);
  71753. return this;
  71754. };
  71755. /**
  71756. * Add a joint to this impostor with a different impostor.
  71757. */
  71758. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  71759. this._joints.push({
  71760. otherImpostor: otherImpostor,
  71761. joint: joint
  71762. });
  71763. if (this._physicsEngine) {
  71764. this._physicsEngine.addJoint(this, otherImpostor, joint);
  71765. }
  71766. return this;
  71767. };
  71768. /**
  71769. * Will keep this body still, in a sleep mode.
  71770. */
  71771. PhysicsImpostor.prototype.sleep = function () {
  71772. if (this._physicsEngine) {
  71773. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  71774. }
  71775. return this;
  71776. };
  71777. /**
  71778. * Wake the body up.
  71779. */
  71780. PhysicsImpostor.prototype.wakeUp = function () {
  71781. if (this._physicsEngine) {
  71782. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  71783. }
  71784. return this;
  71785. };
  71786. PhysicsImpostor.prototype.clone = function (newObject) {
  71787. if (!newObject)
  71788. return null;
  71789. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  71790. };
  71791. PhysicsImpostor.prototype.dispose = function () {
  71792. var _this = this;
  71793. //no dispose if no physics engine is available.
  71794. if (!this._physicsEngine) {
  71795. return;
  71796. }
  71797. this._joints.forEach(function (j) {
  71798. if (_this._physicsEngine) {
  71799. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  71800. }
  71801. });
  71802. //dispose the physics body
  71803. this._physicsEngine.removeImpostor(this);
  71804. if (this.parent) {
  71805. this.parent.forceUpdate();
  71806. }
  71807. else {
  71808. /*this._object.getChildMeshes().forEach(function(mesh) {
  71809. if (mesh.physicsImpostor) {
  71810. if (disposeChildren) {
  71811. mesh.physicsImpostor.dispose();
  71812. mesh.physicsImpostor = null;
  71813. }
  71814. }
  71815. })*/
  71816. }
  71817. this._isDisposed = true;
  71818. };
  71819. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  71820. this._deltaPosition.copyFrom(position);
  71821. };
  71822. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  71823. if (!this._deltaRotation) {
  71824. this._deltaRotation = new BABYLON.Quaternion();
  71825. }
  71826. this._deltaRotation.copyFrom(rotation);
  71827. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  71828. };
  71829. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  71830. if (this._physicsEngine) {
  71831. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  71832. }
  71833. return this;
  71834. };
  71835. PhysicsImpostor.prototype.getRadius = function () {
  71836. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  71837. };
  71838. /**
  71839. * Sync a bone with this impostor
  71840. * @param bone The bone to sync to the impostor.
  71841. * @param boneMesh The mesh that the bone is influencing.
  71842. * @param jointPivot The pivot of the joint / bone in local space.
  71843. * @param distToJoint Optional distance from the impostor to the joint.
  71844. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71845. */
  71846. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  71847. var tempVec = PhysicsImpostor._tmpVecs[0];
  71848. var mesh = this.object;
  71849. if (mesh.rotationQuaternion) {
  71850. if (adjustRotation) {
  71851. var tempQuat = PhysicsImpostor._tmpQuat;
  71852. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  71853. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  71854. }
  71855. else {
  71856. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  71857. }
  71858. }
  71859. tempVec.x = 0;
  71860. tempVec.y = 0;
  71861. tempVec.z = 0;
  71862. if (jointPivot) {
  71863. tempVec.x = jointPivot.x;
  71864. tempVec.y = jointPivot.y;
  71865. tempVec.z = jointPivot.z;
  71866. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  71867. if (distToJoint === undefined || distToJoint === null) {
  71868. distToJoint = jointPivot.length();
  71869. }
  71870. tempVec.x *= distToJoint;
  71871. tempVec.y *= distToJoint;
  71872. tempVec.z *= distToJoint;
  71873. }
  71874. if (bone.getParent()) {
  71875. tempVec.addInPlace(mesh.getAbsolutePosition());
  71876. bone.setAbsolutePosition(tempVec, boneMesh);
  71877. }
  71878. else {
  71879. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  71880. boneMesh.position.x -= tempVec.x;
  71881. boneMesh.position.y -= tempVec.y;
  71882. boneMesh.position.z -= tempVec.z;
  71883. }
  71884. };
  71885. /**
  71886. * Sync impostor to a bone
  71887. * @param bone The bone that the impostor will be synced to.
  71888. * @param boneMesh The mesh that the bone is influencing.
  71889. * @param jointPivot The pivot of the joint / bone in local space.
  71890. * @param distToJoint Optional distance from the impostor to the joint.
  71891. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71892. * @param boneAxis Optional vector3 axis the bone is aligned with
  71893. */
  71894. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  71895. var mesh = this.object;
  71896. if (mesh.rotationQuaternion) {
  71897. if (adjustRotation) {
  71898. var tempQuat = PhysicsImpostor._tmpQuat;
  71899. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  71900. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  71901. }
  71902. else {
  71903. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  71904. }
  71905. }
  71906. var pos = PhysicsImpostor._tmpVecs[0];
  71907. var boneDir = PhysicsImpostor._tmpVecs[1];
  71908. if (!boneAxis) {
  71909. boneAxis = PhysicsImpostor._tmpVecs[2];
  71910. boneAxis.x = 0;
  71911. boneAxis.y = 1;
  71912. boneAxis.z = 0;
  71913. }
  71914. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  71915. bone.getAbsolutePositionToRef(boneMesh, pos);
  71916. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  71917. distToJoint = jointPivot.length();
  71918. }
  71919. if (distToJoint !== undefined && distToJoint !== null) {
  71920. pos.x += boneDir.x * distToJoint;
  71921. pos.y += boneDir.y * distToJoint;
  71922. pos.z += boneDir.z * distToJoint;
  71923. }
  71924. mesh.setAbsolutePosition(pos);
  71925. };
  71926. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  71927. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  71928. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71929. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  71930. //Impostor types
  71931. PhysicsImpostor.NoImpostor = 0;
  71932. PhysicsImpostor.SphereImpostor = 1;
  71933. PhysicsImpostor.BoxImpostor = 2;
  71934. PhysicsImpostor.PlaneImpostor = 3;
  71935. PhysicsImpostor.MeshImpostor = 4;
  71936. PhysicsImpostor.CylinderImpostor = 7;
  71937. PhysicsImpostor.ParticleImpostor = 8;
  71938. PhysicsImpostor.HeightmapImpostor = 9;
  71939. return PhysicsImpostor;
  71940. }());
  71941. BABYLON.PhysicsImpostor = PhysicsImpostor;
  71942. })(BABYLON || (BABYLON = {}));
  71943. //# sourceMappingURL=babylon.physicsImpostor.js.map
  71944. var BABYLON;
  71945. (function (BABYLON) {
  71946. var PhysicsEngine = /** @class */ (function () {
  71947. function PhysicsEngine(gravity, _physicsPlugin) {
  71948. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  71949. this._physicsPlugin = _physicsPlugin;
  71950. //new methods and parameters
  71951. this._impostors = [];
  71952. this._joints = [];
  71953. if (!this._physicsPlugin.isSupported()) {
  71954. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  71955. + "Please make sure it is included.");
  71956. }
  71957. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  71958. this.setGravity(gravity);
  71959. this.setTimeStep();
  71960. }
  71961. PhysicsEngine.prototype.setGravity = function (gravity) {
  71962. this.gravity = gravity;
  71963. this._physicsPlugin.setGravity(this.gravity);
  71964. };
  71965. /**
  71966. * Set the time step of the physics engine.
  71967. * default is 1/60.
  71968. * To slow it down, enter 1/600 for example.
  71969. * To speed it up, 1/30
  71970. * @param {number} newTimeStep the new timestep to apply to this world.
  71971. */
  71972. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  71973. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  71974. this._physicsPlugin.setTimeStep(newTimeStep);
  71975. };
  71976. /**
  71977. * Get the time step of the physics engine.
  71978. */
  71979. PhysicsEngine.prototype.getTimeStep = function () {
  71980. return this._physicsPlugin.getTimeStep();
  71981. };
  71982. PhysicsEngine.prototype.dispose = function () {
  71983. this._impostors.forEach(function (impostor) {
  71984. impostor.dispose();
  71985. });
  71986. this._physicsPlugin.dispose();
  71987. };
  71988. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  71989. return this._physicsPlugin.name;
  71990. };
  71991. /**
  71992. * Adding a new impostor for the impostor tracking.
  71993. * This will be done by the impostor itself.
  71994. * @param {PhysicsImpostor} impostor the impostor to add
  71995. */
  71996. PhysicsEngine.prototype.addImpostor = function (impostor) {
  71997. impostor.uniqueId = this._impostors.push(impostor);
  71998. //if no parent, generate the body
  71999. if (!impostor.parent) {
  72000. this._physicsPlugin.generatePhysicsBody(impostor);
  72001. }
  72002. };
  72003. /**
  72004. * Remove an impostor from the engine.
  72005. * This impostor and its mesh will not longer be updated by the physics engine.
  72006. * @param {PhysicsImpostor} impostor the impostor to remove
  72007. */
  72008. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  72009. var index = this._impostors.indexOf(impostor);
  72010. if (index > -1) {
  72011. var removed = this._impostors.splice(index, 1);
  72012. //Is it needed?
  72013. if (removed.length) {
  72014. //this will also remove it from the world.
  72015. removed[0].physicsBody = null;
  72016. }
  72017. }
  72018. };
  72019. /**
  72020. * Add a joint to the physics engine
  72021. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  72022. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  72023. * @param {PhysicsJoint} the joint that will connect both impostors.
  72024. */
  72025. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  72026. var impostorJoint = {
  72027. mainImpostor: mainImpostor,
  72028. connectedImpostor: connectedImpostor,
  72029. joint: joint
  72030. };
  72031. joint.physicsPlugin = this._physicsPlugin;
  72032. this._joints.push(impostorJoint);
  72033. this._physicsPlugin.generateJoint(impostorJoint);
  72034. };
  72035. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  72036. var matchingJoints = this._joints.filter(function (impostorJoint) {
  72037. return (impostorJoint.connectedImpostor === connectedImpostor
  72038. && impostorJoint.joint === joint
  72039. && impostorJoint.mainImpostor === mainImpostor);
  72040. });
  72041. if (matchingJoints.length) {
  72042. this._physicsPlugin.removeJoint(matchingJoints[0]);
  72043. //TODO remove it from the list as well
  72044. }
  72045. };
  72046. /**
  72047. * Called by the scene. no need to call it.
  72048. */
  72049. PhysicsEngine.prototype._step = function (delta) {
  72050. var _this = this;
  72051. //check if any mesh has no body / requires an update
  72052. this._impostors.forEach(function (impostor) {
  72053. if (impostor.isBodyInitRequired()) {
  72054. _this._physicsPlugin.generatePhysicsBody(impostor);
  72055. }
  72056. });
  72057. if (delta > 0.1) {
  72058. delta = 0.1;
  72059. }
  72060. else if (delta <= 0) {
  72061. delta = 1.0 / 60.0;
  72062. }
  72063. this._physicsPlugin.executeStep(delta, this._impostors);
  72064. };
  72065. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  72066. return this._physicsPlugin;
  72067. };
  72068. PhysicsEngine.prototype.getImpostors = function () {
  72069. return this._impostors;
  72070. };
  72071. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  72072. for (var i = 0; i < this._impostors.length; ++i) {
  72073. if (this._impostors[i].object === object) {
  72074. return this._impostors[i];
  72075. }
  72076. }
  72077. return null;
  72078. };
  72079. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  72080. for (var i = 0; i < this._impostors.length; ++i) {
  72081. if (this._impostors[i].physicsBody === body) {
  72082. return this._impostors[i];
  72083. }
  72084. }
  72085. return null;
  72086. };
  72087. // Statics
  72088. PhysicsEngine.Epsilon = 0.001;
  72089. return PhysicsEngine;
  72090. }());
  72091. BABYLON.PhysicsEngine = PhysicsEngine;
  72092. })(BABYLON || (BABYLON = {}));
  72093. //# sourceMappingURL=babylon.physicsEngine.js.map
  72094. var BABYLON;
  72095. (function (BABYLON) {
  72096. var PhysicsHelper = /** @class */ (function () {
  72097. function PhysicsHelper(scene) {
  72098. this._scene = scene;
  72099. this._physicsEngine = this._scene.getPhysicsEngine();
  72100. if (!this._physicsEngine) {
  72101. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  72102. }
  72103. }
  72104. /**
  72105. * @param {Vector3} origin the origin of the explosion
  72106. * @param {number} radius the explosion radius
  72107. * @param {number} strength the explosion strength
  72108. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72109. */
  72110. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  72111. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72112. if (!this._physicsEngine) {
  72113. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  72114. return null;
  72115. }
  72116. var impostors = this._physicsEngine.getImpostors();
  72117. if (impostors.length === 0) {
  72118. return null;
  72119. }
  72120. var event = new PhysicsRadialExplosionEvent(this._scene);
  72121. impostors.forEach(function (impostor) {
  72122. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  72123. if (!impostorForceAndContactPoint) {
  72124. return;
  72125. }
  72126. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72127. });
  72128. event.dispose(false);
  72129. return event;
  72130. };
  72131. /**
  72132. * @param {Vector3} origin the origin of the explosion
  72133. * @param {number} radius the explosion radius
  72134. * @param {number} strength the explosion strength
  72135. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72136. */
  72137. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  72138. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72139. if (!this._physicsEngine) {
  72140. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72141. return null;
  72142. }
  72143. var impostors = this._physicsEngine.getImpostors();
  72144. if (impostors.length === 0) {
  72145. return null;
  72146. }
  72147. var event = new PhysicsRadialExplosionEvent(this._scene);
  72148. impostors.forEach(function (impostor) {
  72149. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  72150. if (!impostorForceAndContactPoint) {
  72151. return;
  72152. }
  72153. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72154. });
  72155. event.dispose(false);
  72156. return event;
  72157. };
  72158. /**
  72159. * @param {Vector3} origin the origin of the explosion
  72160. * @param {number} radius the explosion radius
  72161. * @param {number} strength the explosion strength
  72162. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72163. */
  72164. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  72165. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72166. if (!this._physicsEngine) {
  72167. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72168. return null;
  72169. }
  72170. var impostors = this._physicsEngine.getImpostors();
  72171. if (impostors.length === 0) {
  72172. return null;
  72173. }
  72174. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  72175. event.dispose(false);
  72176. return event;
  72177. };
  72178. /**
  72179. * @param {Vector3} origin the origin of the updraft
  72180. * @param {number} radius the radius of the updraft
  72181. * @param {number} strength the strength of the updraft
  72182. * @param {number} height the height of the updraft
  72183. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  72184. */
  72185. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  72186. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  72187. if (!this._physicsEngine) {
  72188. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72189. return null;
  72190. }
  72191. if (this._physicsEngine.getImpostors().length === 0) {
  72192. return null;
  72193. }
  72194. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  72195. event.dispose(false);
  72196. return event;
  72197. };
  72198. /**
  72199. * @param {Vector3} origin the of the vortex
  72200. * @param {number} radius the radius of the vortex
  72201. * @param {number} strength the strength of the vortex
  72202. * @param {number} height the height of the vortex
  72203. */
  72204. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  72205. if (!this._physicsEngine) {
  72206. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72207. return null;
  72208. }
  72209. if (this._physicsEngine.getImpostors().length === 0) {
  72210. return null;
  72211. }
  72212. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  72213. event.dispose(false);
  72214. return event;
  72215. };
  72216. return PhysicsHelper;
  72217. }());
  72218. BABYLON.PhysicsHelper = PhysicsHelper;
  72219. /***** Radial explosion *****/
  72220. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  72221. function PhysicsRadialExplosionEvent(scene) {
  72222. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  72223. this._rays = [];
  72224. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  72225. this._scene = scene;
  72226. }
  72227. /**
  72228. * Returns the data related to the radial explosion event (sphere & rays).
  72229. * @returns {PhysicsRadialExplosionEventData}
  72230. */
  72231. PhysicsRadialExplosionEvent.prototype.getData = function () {
  72232. this._dataFetched = true;
  72233. return {
  72234. sphere: this._sphere,
  72235. rays: this._rays,
  72236. };
  72237. };
  72238. /**
  72239. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  72240. * @param impostor
  72241. * @param {Vector3} origin the origin of the explosion
  72242. * @param {number} radius the explosion radius
  72243. * @param {number} strength the explosion strength
  72244. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  72245. * @returns {Nullable<PhysicsForceAndContactPoint>}
  72246. */
  72247. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  72248. if (impostor.mass === 0) {
  72249. return null;
  72250. }
  72251. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  72252. return null;
  72253. }
  72254. if (impostor.object.getClassName() !== 'Mesh') {
  72255. return null;
  72256. }
  72257. var impostorObject = impostor.object;
  72258. var impostorObjectCenter = impostor.getObjectCenter();
  72259. var direction = impostorObjectCenter.subtract(origin);
  72260. var ray = new BABYLON.Ray(origin, direction, radius);
  72261. this._rays.push(ray);
  72262. var hit = ray.intersectsMesh(impostorObject);
  72263. var contactPoint = hit.pickedPoint;
  72264. if (!contactPoint) {
  72265. return null;
  72266. }
  72267. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  72268. if (distanceFromOrigin > radius) {
  72269. return null;
  72270. }
  72271. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  72272. ? strength
  72273. : strength * (1 - (distanceFromOrigin / radius));
  72274. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72275. return { force: force, contactPoint: contactPoint };
  72276. };
  72277. /**
  72278. * Disposes the sphere.
  72279. * @param {bolean} force
  72280. */
  72281. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  72282. var _this = this;
  72283. if (force === void 0) { force = true; }
  72284. if (force) {
  72285. this._sphere.dispose();
  72286. }
  72287. else {
  72288. setTimeout(function () {
  72289. if (!_this._dataFetched) {
  72290. _this._sphere.dispose();
  72291. }
  72292. }, 0);
  72293. }
  72294. };
  72295. /*** Helpers ***/
  72296. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  72297. if (!this._sphere) {
  72298. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  72299. this._sphere.isVisible = false;
  72300. }
  72301. };
  72302. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  72303. var impostorObject = impostor.object;
  72304. this._prepareSphere();
  72305. this._sphere.position = origin;
  72306. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  72307. this._sphere._updateBoundingInfo();
  72308. this._sphere.computeWorldMatrix(true);
  72309. return this._sphere.intersectsMesh(impostorObject, true);
  72310. };
  72311. return PhysicsRadialExplosionEvent;
  72312. }());
  72313. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  72314. /***** Gravitational Field *****/
  72315. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  72316. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  72317. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72318. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72319. this._physicsHelper = physicsHelper;
  72320. this._scene = scene;
  72321. this._origin = origin;
  72322. this._radius = radius;
  72323. this._strength = strength;
  72324. this._falloff = falloff;
  72325. this._tickCallback = this._tick.bind(this);
  72326. }
  72327. /**
  72328. * Returns the data related to the gravitational field event (sphere).
  72329. * @returns {PhysicsGravitationalFieldEventData}
  72330. */
  72331. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  72332. this._dataFetched = true;
  72333. return {
  72334. sphere: this._sphere,
  72335. };
  72336. };
  72337. /**
  72338. * Enables the gravitational field.
  72339. */
  72340. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  72341. this._tickCallback.call(this);
  72342. this._scene.registerBeforeRender(this._tickCallback);
  72343. };
  72344. /**
  72345. * Disables the gravitational field.
  72346. */
  72347. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  72348. this._scene.unregisterBeforeRender(this._tickCallback);
  72349. };
  72350. /**
  72351. * Disposes the sphere.
  72352. * @param {bolean} force
  72353. */
  72354. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  72355. var _this = this;
  72356. if (force === void 0) { force = true; }
  72357. if (force) {
  72358. this._sphere.dispose();
  72359. }
  72360. else {
  72361. setTimeout(function () {
  72362. if (!_this._dataFetched) {
  72363. _this._sphere.dispose();
  72364. }
  72365. }, 0);
  72366. }
  72367. };
  72368. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  72369. // Since the params won't change, we fetch the event only once
  72370. if (this._sphere) {
  72371. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72372. }
  72373. else {
  72374. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72375. if (radialExplosionEvent) {
  72376. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  72377. }
  72378. }
  72379. };
  72380. return PhysicsGravitationalFieldEvent;
  72381. }());
  72382. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  72383. /***** Updraft *****/
  72384. var PhysicsUpdraftEvent = /** @class */ (function () {
  72385. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  72386. this._scene = _scene;
  72387. this._origin = _origin;
  72388. this._radius = _radius;
  72389. this._strength = _strength;
  72390. this._height = _height;
  72391. this._updraftMode = _updraftMode;
  72392. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72393. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  72394. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72395. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72396. this._physicsEngine = this._scene.getPhysicsEngine();
  72397. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72398. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72399. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72400. this._originDirection = this._origin.subtract(this._originTop).normalize();
  72401. }
  72402. this._tickCallback = this._tick.bind(this);
  72403. }
  72404. /**
  72405. * Returns the data related to the updraft event (cylinder).
  72406. * @returns {PhysicsUpdraftEventData}
  72407. */
  72408. PhysicsUpdraftEvent.prototype.getData = function () {
  72409. this._dataFetched = true;
  72410. return {
  72411. cylinder: this._cylinder,
  72412. };
  72413. };
  72414. /**
  72415. * Enables the updraft.
  72416. */
  72417. PhysicsUpdraftEvent.prototype.enable = function () {
  72418. this._tickCallback.call(this);
  72419. this._scene.registerBeforeRender(this._tickCallback);
  72420. };
  72421. /**
  72422. * Disables the cortex.
  72423. */
  72424. PhysicsUpdraftEvent.prototype.disable = function () {
  72425. this._scene.unregisterBeforeRender(this._tickCallback);
  72426. };
  72427. /**
  72428. * Disposes the sphere.
  72429. * @param {bolean} force
  72430. */
  72431. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  72432. var _this = this;
  72433. if (force === void 0) { force = true; }
  72434. if (force) {
  72435. this._cylinder.dispose();
  72436. }
  72437. else {
  72438. setTimeout(function () {
  72439. if (!_this._dataFetched) {
  72440. _this._cylinder.dispose();
  72441. }
  72442. }, 0);
  72443. }
  72444. };
  72445. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72446. if (impostor.mass === 0) {
  72447. return null;
  72448. }
  72449. if (!this._intersectsWithCylinder(impostor)) {
  72450. return null;
  72451. }
  72452. var impostorObjectCenter = impostor.getObjectCenter();
  72453. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72454. var direction = this._originDirection;
  72455. }
  72456. else {
  72457. var direction = impostorObjectCenter.subtract(this._originTop);
  72458. }
  72459. var multiplier = this._strength * -1;
  72460. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72461. return { force: force, contactPoint: impostorObjectCenter };
  72462. };
  72463. PhysicsUpdraftEvent.prototype._tick = function () {
  72464. var _this = this;
  72465. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72466. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72467. if (!impostorForceAndContactPoint) {
  72468. return;
  72469. }
  72470. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72471. });
  72472. };
  72473. /*** Helpers ***/
  72474. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  72475. if (!this._cylinder) {
  72476. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  72477. height: this._height,
  72478. diameter: this._radius * 2,
  72479. }, this._scene);
  72480. this._cylinder.isVisible = false;
  72481. }
  72482. };
  72483. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  72484. var impostorObject = impostor.object;
  72485. this._prepareCylinder();
  72486. this._cylinder.position = this._cylinderPosition;
  72487. return this._cylinder.intersectsMesh(impostorObject, true);
  72488. };
  72489. return PhysicsUpdraftEvent;
  72490. }());
  72491. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  72492. /***** Vortex *****/
  72493. var PhysicsVortexEvent = /** @class */ (function () {
  72494. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  72495. this._scene = _scene;
  72496. this._origin = _origin;
  72497. this._radius = _radius;
  72498. this._strength = _strength;
  72499. this._height = _height;
  72500. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72501. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  72502. this._updraftMultiplier = 0.02;
  72503. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72504. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72505. this._physicsEngine = this._scene.getPhysicsEngine();
  72506. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72507. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72508. this._tickCallback = this._tick.bind(this);
  72509. }
  72510. /**
  72511. * Returns the data related to the vortex event (cylinder).
  72512. * @returns {PhysicsVortexEventData}
  72513. */
  72514. PhysicsVortexEvent.prototype.getData = function () {
  72515. this._dataFetched = true;
  72516. return {
  72517. cylinder: this._cylinder,
  72518. };
  72519. };
  72520. /**
  72521. * Enables the vortex.
  72522. */
  72523. PhysicsVortexEvent.prototype.enable = function () {
  72524. this._tickCallback.call(this);
  72525. this._scene.registerBeforeRender(this._tickCallback);
  72526. };
  72527. /**
  72528. * Disables the cortex.
  72529. */
  72530. PhysicsVortexEvent.prototype.disable = function () {
  72531. this._scene.unregisterBeforeRender(this._tickCallback);
  72532. };
  72533. /**
  72534. * Disposes the sphere.
  72535. * @param {bolean} force
  72536. */
  72537. PhysicsVortexEvent.prototype.dispose = function (force) {
  72538. var _this = this;
  72539. if (force === void 0) { force = true; }
  72540. if (force) {
  72541. this._cylinder.dispose();
  72542. }
  72543. else {
  72544. setTimeout(function () {
  72545. if (!_this._dataFetched) {
  72546. _this._cylinder.dispose();
  72547. }
  72548. }, 0);
  72549. }
  72550. };
  72551. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72552. if (impostor.mass === 0) {
  72553. return null;
  72554. }
  72555. if (!this._intersectsWithCylinder(impostor)) {
  72556. return null;
  72557. }
  72558. if (impostor.object.getClassName() !== 'Mesh') {
  72559. return null;
  72560. }
  72561. var impostorObject = impostor.object;
  72562. var impostorObjectCenter = impostor.getObjectCenter();
  72563. 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)
  72564. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  72565. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  72566. var hit = ray.intersectsMesh(impostorObject);
  72567. var contactPoint = hit.pickedPoint;
  72568. if (!contactPoint) {
  72569. return null;
  72570. }
  72571. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  72572. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  72573. var directionToOrigin = contactPoint.normalize();
  72574. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72575. directionToOrigin = directionToOrigin.negate();
  72576. }
  72577. // TODO: find a more physically based solution
  72578. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72579. var forceX = directionToOrigin.x * this._strength / 8;
  72580. var forceY = directionToOrigin.y * this._updraftMultiplier;
  72581. var forceZ = directionToOrigin.z * this._strength / 8;
  72582. }
  72583. else {
  72584. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  72585. var forceY = this._originTop.y * this._updraftMultiplier;
  72586. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  72587. }
  72588. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  72589. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  72590. return { force: force, contactPoint: impostorObjectCenter };
  72591. };
  72592. PhysicsVortexEvent.prototype._tick = function () {
  72593. var _this = this;
  72594. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72595. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72596. if (!impostorForceAndContactPoint) {
  72597. return;
  72598. }
  72599. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72600. });
  72601. };
  72602. /*** Helpers ***/
  72603. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  72604. if (!this._cylinder) {
  72605. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  72606. height: this._height,
  72607. diameter: this._radius * 2,
  72608. }, this._scene);
  72609. this._cylinder.isVisible = false;
  72610. }
  72611. };
  72612. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  72613. var impostorObject = impostor.object;
  72614. this._prepareCylinder();
  72615. this._cylinder.position = this._cylinderPosition;
  72616. return this._cylinder.intersectsMesh(impostorObject, true);
  72617. };
  72618. return PhysicsVortexEvent;
  72619. }());
  72620. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  72621. /***** Enums *****/
  72622. /**
  72623. * The strenght of the force in correspondence to the distance of the affected object
  72624. */
  72625. var PhysicsRadialImpulseFalloff;
  72626. (function (PhysicsRadialImpulseFalloff) {
  72627. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  72628. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  72629. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  72630. /**
  72631. * The strenght of the force in correspondence to the distance of the affected object
  72632. */
  72633. var PhysicsUpdraftMode;
  72634. (function (PhysicsUpdraftMode) {
  72635. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  72636. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  72637. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  72638. })(BABYLON || (BABYLON = {}));
  72639. //# sourceMappingURL=babylon.physicsHelper.js.map
  72640. var BABYLON;
  72641. (function (BABYLON) {
  72642. var CannonJSPlugin = /** @class */ (function () {
  72643. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  72644. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  72645. if (iterations === void 0) { iterations = 10; }
  72646. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  72647. this.name = "CannonJSPlugin";
  72648. this._physicsMaterials = new Array();
  72649. this._fixedTimeStep = 1 / 60;
  72650. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  72651. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  72652. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  72653. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  72654. this._tmpPosition = BABYLON.Vector3.Zero();
  72655. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  72656. this._tmpUnityRotation = new BABYLON.Quaternion();
  72657. if (!this.isSupported()) {
  72658. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  72659. return;
  72660. }
  72661. this._extendNamespace();
  72662. this.world = new this.BJSCANNON.World();
  72663. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  72664. this.world.solver.iterations = iterations;
  72665. }
  72666. CannonJSPlugin.prototype.setGravity = function (gravity) {
  72667. this.world.gravity.copy(gravity);
  72668. };
  72669. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  72670. this._fixedTimeStep = timeStep;
  72671. };
  72672. CannonJSPlugin.prototype.getTimeStep = function () {
  72673. return this._fixedTimeStep;
  72674. };
  72675. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  72676. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  72677. };
  72678. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72679. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72680. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72681. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  72682. };
  72683. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72684. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72685. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72686. impostor.physicsBody.applyForce(impulse, worldPoint);
  72687. };
  72688. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72689. //parent-child relationship. Does this impostor has a parent impostor?
  72690. if (impostor.parent) {
  72691. if (impostor.physicsBody) {
  72692. this.removePhysicsBody(impostor);
  72693. //TODO is that needed?
  72694. impostor.forceUpdate();
  72695. }
  72696. return;
  72697. }
  72698. //should a new body be created for this impostor?
  72699. if (impostor.isBodyInitRequired()) {
  72700. var shape = this._createShape(impostor);
  72701. //unregister events, if body is being changed
  72702. var oldBody = impostor.physicsBody;
  72703. if (oldBody) {
  72704. this.removePhysicsBody(impostor);
  72705. }
  72706. //create the body and material
  72707. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  72708. var bodyCreationObject = {
  72709. mass: impostor.getParam("mass"),
  72710. material: material
  72711. };
  72712. // A simple extend, in case native options were used.
  72713. var nativeOptions = impostor.getParam("nativeOptions");
  72714. for (var key in nativeOptions) {
  72715. if (nativeOptions.hasOwnProperty(key)) {
  72716. bodyCreationObject[key] = nativeOptions[key];
  72717. }
  72718. }
  72719. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  72720. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  72721. this.world.addEventListener("preStep", impostor.beforeStep);
  72722. this.world.addEventListener("postStep", impostor.afterStep);
  72723. impostor.physicsBody.addShape(shape);
  72724. this.world.add(impostor.physicsBody);
  72725. //try to keep the body moving in the right direction by taking old properties.
  72726. //Should be tested!
  72727. if (oldBody) {
  72728. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  72729. impostor.physicsBody[param].copy(oldBody[param]);
  72730. });
  72731. }
  72732. this._processChildMeshes(impostor);
  72733. }
  72734. //now update the body's transformation
  72735. this._updatePhysicsBodyTransformation(impostor);
  72736. };
  72737. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  72738. var _this = this;
  72739. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  72740. var currentRotation = mainImpostor.object.rotationQuaternion;
  72741. if (meshChildren.length) {
  72742. var processMesh = function (localPosition, mesh) {
  72743. if (!currentRotation || !mesh.rotationQuaternion) {
  72744. return;
  72745. }
  72746. var childImpostor = mesh.getPhysicsImpostor();
  72747. if (childImpostor) {
  72748. var parent = childImpostor.parent;
  72749. if (parent !== mainImpostor) {
  72750. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  72751. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  72752. if (childImpostor.physicsBody) {
  72753. _this.removePhysicsBody(childImpostor);
  72754. childImpostor.physicsBody = null;
  72755. }
  72756. childImpostor.parent = mainImpostor;
  72757. childImpostor.resetUpdateFlags();
  72758. 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));
  72759. //Add the mass of the children.
  72760. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  72761. }
  72762. }
  72763. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  72764. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  72765. };
  72766. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  72767. }
  72768. };
  72769. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72770. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  72771. this.world.removeEventListener("preStep", impostor.beforeStep);
  72772. this.world.removeEventListener("postStep", impostor.afterStep);
  72773. this.world.remove(impostor.physicsBody);
  72774. };
  72775. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72776. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72777. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72778. if (!mainBody || !connectedBody) {
  72779. return;
  72780. }
  72781. var constraint;
  72782. var jointData = impostorJoint.joint.jointData;
  72783. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  72784. var constraintData = {
  72785. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  72786. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  72787. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  72788. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  72789. maxForce: jointData.nativeParams.maxForce,
  72790. collideConnected: !!jointData.collision
  72791. };
  72792. switch (impostorJoint.joint.type) {
  72793. case BABYLON.PhysicsJoint.HingeJoint:
  72794. case BABYLON.PhysicsJoint.Hinge2Joint:
  72795. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  72796. break;
  72797. case BABYLON.PhysicsJoint.DistanceJoint:
  72798. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  72799. break;
  72800. case BABYLON.PhysicsJoint.SpringJoint:
  72801. var springData = jointData;
  72802. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  72803. restLength: springData.length,
  72804. stiffness: springData.stiffness,
  72805. damping: springData.damping,
  72806. localAnchorA: constraintData.pivotA,
  72807. localAnchorB: constraintData.pivotB
  72808. });
  72809. break;
  72810. case BABYLON.PhysicsJoint.LockJoint:
  72811. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  72812. break;
  72813. case BABYLON.PhysicsJoint.PointToPointJoint:
  72814. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72815. default:
  72816. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  72817. break;
  72818. }
  72819. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  72820. constraint.collideConnected = !!jointData.collision;
  72821. impostorJoint.joint.physicsJoint = constraint;
  72822. //don't add spring as constraint, as it is not one.
  72823. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  72824. this.world.addConstraint(constraint);
  72825. }
  72826. else {
  72827. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  72828. constraint.applyForce();
  72829. });
  72830. }
  72831. };
  72832. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72833. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  72834. };
  72835. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  72836. var index;
  72837. var mat;
  72838. for (index = 0; index < this._physicsMaterials.length; index++) {
  72839. mat = this._physicsMaterials[index];
  72840. if (mat.friction === friction && mat.restitution === restitution) {
  72841. return mat;
  72842. }
  72843. }
  72844. var currentMat = new this.BJSCANNON.Material(name);
  72845. currentMat.friction = friction;
  72846. currentMat.restitution = restitution;
  72847. this._physicsMaterials.push(currentMat);
  72848. return currentMat;
  72849. };
  72850. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  72851. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  72852. };
  72853. CannonJSPlugin.prototype._createShape = function (impostor) {
  72854. var object = impostor.object;
  72855. var returnValue;
  72856. var extendSize = impostor.getObjectExtendSize();
  72857. switch (impostor.type) {
  72858. case BABYLON.PhysicsImpostor.SphereImpostor:
  72859. var radiusX = extendSize.x;
  72860. var radiusY = extendSize.y;
  72861. var radiusZ = extendSize.z;
  72862. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  72863. break;
  72864. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  72865. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72866. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  72867. break;
  72868. case BABYLON.PhysicsImpostor.BoxImpostor:
  72869. var box = extendSize.scale(0.5);
  72870. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  72871. break;
  72872. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72873. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  72874. returnValue = new this.BJSCANNON.Plane();
  72875. break;
  72876. case BABYLON.PhysicsImpostor.MeshImpostor:
  72877. // should transform the vertex data to world coordinates!!
  72878. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  72879. var rawFaces = object.getIndices ? object.getIndices() : [];
  72880. if (!rawVerts)
  72881. return;
  72882. // get only scale! so the object could transform correctly.
  72883. var oldPosition = object.position.clone();
  72884. var oldRotation = object.rotation && object.rotation.clone();
  72885. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  72886. object.position.copyFromFloats(0, 0, 0);
  72887. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72888. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72889. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72890. var transform = object.computeWorldMatrix(true);
  72891. // convert rawVerts to object space
  72892. var temp = new Array();
  72893. var index;
  72894. for (index = 0; index < rawVerts.length; index += 3) {
  72895. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  72896. }
  72897. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  72898. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  72899. //now set back the transformation!
  72900. object.position.copyFrom(oldPosition);
  72901. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  72902. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  72903. break;
  72904. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  72905. var oldPosition2 = object.position.clone();
  72906. var oldRotation2 = object.rotation && object.rotation.clone();
  72907. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  72908. object.position.copyFromFloats(0, 0, 0);
  72909. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72910. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72911. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72912. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  72913. returnValue = this._createHeightmap(object);
  72914. object.position.copyFrom(oldPosition2);
  72915. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  72916. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  72917. object.computeWorldMatrix(true);
  72918. break;
  72919. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72920. returnValue = new this.BJSCANNON.Particle();
  72921. break;
  72922. }
  72923. return returnValue;
  72924. };
  72925. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  72926. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  72927. var transform = object.computeWorldMatrix(true);
  72928. // convert rawVerts to object space
  72929. var temp = new Array();
  72930. var index;
  72931. for (index = 0; index < pos.length; index += 3) {
  72932. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  72933. }
  72934. pos = temp;
  72935. var matrix = new Array();
  72936. //For now pointDepth will not be used and will be automatically calculated.
  72937. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  72938. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  72939. var boundingInfo = object.getBoundingInfo();
  72940. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  72941. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  72942. var elementSize = dim * 2 / arraySize;
  72943. for (var i = 0; i < pos.length; i = i + 3) {
  72944. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  72945. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  72946. var y = -pos[i + 2] + minY;
  72947. if (!matrix[x]) {
  72948. matrix[x] = [];
  72949. }
  72950. if (!matrix[x][z]) {
  72951. matrix[x][z] = y;
  72952. }
  72953. matrix[x][z] = Math.max(y, matrix[x][z]);
  72954. }
  72955. for (var x = 0; x <= arraySize; ++x) {
  72956. if (!matrix[x]) {
  72957. var loc = 1;
  72958. while (!matrix[(x + loc) % arraySize]) {
  72959. loc++;
  72960. }
  72961. matrix[x] = matrix[(x + loc) % arraySize].slice();
  72962. //console.log("missing x", x);
  72963. }
  72964. for (var z = 0; z <= arraySize; ++z) {
  72965. if (!matrix[x][z]) {
  72966. var loc = 1;
  72967. var newValue;
  72968. while (newValue === undefined) {
  72969. newValue = matrix[x][(z + loc++) % arraySize];
  72970. }
  72971. matrix[x][z] = newValue;
  72972. }
  72973. }
  72974. }
  72975. var shape = new this.BJSCANNON.Heightfield(matrix, {
  72976. elementSize: elementSize
  72977. });
  72978. //For future reference, needed for body transformation
  72979. shape.minY = minY;
  72980. return shape;
  72981. };
  72982. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  72983. var object = impostor.object;
  72984. //make sure it is updated...
  72985. object.computeWorldMatrix && object.computeWorldMatrix(true);
  72986. // The delta between the mesh position and the mesh bounding box center
  72987. var bInfo = object.getBoundingInfo();
  72988. if (!bInfo)
  72989. return;
  72990. var center = impostor.getObjectCenter();
  72991. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  72992. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  72993. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  72994. this._tmpPosition.copyFrom(center);
  72995. var quaternion = object.rotationQuaternion;
  72996. if (!quaternion) {
  72997. return;
  72998. }
  72999. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  73000. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  73001. //-90 DEG in X, precalculated
  73002. quaternion = quaternion.multiply(this._minus90X);
  73003. //Invert! (Precalculated, 90 deg in X)
  73004. //No need to clone. this will never change.
  73005. impostor.setDeltaRotation(this._plus90X);
  73006. }
  73007. //If it is a heightfield, if should be centered.
  73008. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  73009. var mesh = object;
  73010. var boundingInfo = mesh.getBoundingInfo();
  73011. //calculate the correct body position:
  73012. var rotationQuaternion = mesh.rotationQuaternion;
  73013. mesh.rotationQuaternion = this._tmpUnityRotation;
  73014. mesh.computeWorldMatrix(true);
  73015. //get original center with no rotation
  73016. var c = center.clone();
  73017. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  73018. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  73019. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  73020. mesh.setPivotMatrix(p);
  73021. mesh.computeWorldMatrix(true);
  73022. //calculate the translation
  73023. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  73024. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  73025. //add it inverted to the delta
  73026. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  73027. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  73028. //rotation is back
  73029. mesh.rotationQuaternion = rotationQuaternion;
  73030. mesh.setPivotMatrix(oldPivot);
  73031. mesh.computeWorldMatrix(true);
  73032. }
  73033. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  73034. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  73035. //this._tmpPosition.copyFrom(object.position);
  73036. }
  73037. impostor.setDeltaPosition(this._tmpDeltaPosition);
  73038. //Now update the impostor object
  73039. impostor.physicsBody.position.copy(this._tmpPosition);
  73040. impostor.physicsBody.quaternion.copy(quaternion);
  73041. };
  73042. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73043. impostor.object.position.copyFrom(impostor.physicsBody.position);
  73044. if (impostor.object.rotationQuaternion) {
  73045. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  73046. }
  73047. };
  73048. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73049. impostor.physicsBody.position.copy(newPosition);
  73050. impostor.physicsBody.quaternion.copy(newRotation);
  73051. };
  73052. CannonJSPlugin.prototype.isSupported = function () {
  73053. return this.BJSCANNON !== undefined;
  73054. };
  73055. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73056. impostor.physicsBody.velocity.copy(velocity);
  73057. };
  73058. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73059. impostor.physicsBody.angularVelocity.copy(velocity);
  73060. };
  73061. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73062. var v = impostor.physicsBody.velocity;
  73063. if (!v) {
  73064. return null;
  73065. }
  73066. return new BABYLON.Vector3(v.x, v.y, v.z);
  73067. };
  73068. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73069. var v = impostor.physicsBody.angularVelocity;
  73070. if (!v) {
  73071. return null;
  73072. }
  73073. return new BABYLON.Vector3(v.x, v.y, v.z);
  73074. };
  73075. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73076. impostor.physicsBody.mass = mass;
  73077. impostor.physicsBody.updateMassProperties();
  73078. };
  73079. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  73080. return impostor.physicsBody.mass;
  73081. };
  73082. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  73083. return impostor.physicsBody.material.friction;
  73084. };
  73085. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73086. impostor.physicsBody.material.friction = friction;
  73087. };
  73088. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73089. return impostor.physicsBody.material.restitution;
  73090. };
  73091. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73092. impostor.physicsBody.material.restitution = restitution;
  73093. };
  73094. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  73095. impostor.physicsBody.sleep();
  73096. };
  73097. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  73098. impostor.physicsBody.wakeUp();
  73099. };
  73100. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73101. joint.physicsJoint.distance = maxDistance;
  73102. };
  73103. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  73104. // if (!motorIndex) {
  73105. // joint.physicsJoint.enableMotor();
  73106. // }
  73107. // }
  73108. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  73109. // if (!motorIndex) {
  73110. // joint.physicsJoint.disableMotor();
  73111. // }
  73112. // }
  73113. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73114. if (!motorIndex) {
  73115. joint.physicsJoint.enableMotor();
  73116. joint.physicsJoint.setMotorSpeed(speed);
  73117. if (maxForce) {
  73118. this.setLimit(joint, maxForce);
  73119. }
  73120. }
  73121. };
  73122. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  73123. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  73124. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  73125. };
  73126. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73127. var body = impostor.physicsBody;
  73128. mesh.position.x = body.position.x;
  73129. mesh.position.y = body.position.y;
  73130. mesh.position.z = body.position.z;
  73131. if (mesh.rotationQuaternion) {
  73132. mesh.rotationQuaternion.x = body.quaternion.x;
  73133. mesh.rotationQuaternion.y = body.quaternion.y;
  73134. mesh.rotationQuaternion.z = body.quaternion.z;
  73135. mesh.rotationQuaternion.w = body.quaternion.w;
  73136. }
  73137. };
  73138. CannonJSPlugin.prototype.getRadius = function (impostor) {
  73139. var shape = impostor.physicsBody.shapes[0];
  73140. return shape.boundingSphereRadius;
  73141. };
  73142. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73143. var shape = impostor.physicsBody.shapes[0];
  73144. result.x = shape.halfExtents.x * 2;
  73145. result.y = shape.halfExtents.y * 2;
  73146. result.z = shape.halfExtents.z * 2;
  73147. };
  73148. CannonJSPlugin.prototype.dispose = function () {
  73149. };
  73150. CannonJSPlugin.prototype._extendNamespace = function () {
  73151. //this will force cannon to execute at least one step when using interpolation
  73152. var step_tmp1 = new this.BJSCANNON.Vec3();
  73153. var Engine = this.BJSCANNON;
  73154. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  73155. maxSubSteps = maxSubSteps || 10;
  73156. timeSinceLastCalled = timeSinceLastCalled || 0;
  73157. if (timeSinceLastCalled === 0) {
  73158. this.internalStep(dt);
  73159. this.time += dt;
  73160. }
  73161. else {
  73162. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  73163. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  73164. var t0 = performance.now();
  73165. for (var i = 0; i !== internalSteps; i++) {
  73166. this.internalStep(dt);
  73167. if (performance.now() - t0 > dt * 1000) {
  73168. break;
  73169. }
  73170. }
  73171. this.time += timeSinceLastCalled;
  73172. var h = this.time % dt;
  73173. var h_div_dt = h / dt;
  73174. var interpvelo = step_tmp1;
  73175. var bodies = this.bodies;
  73176. for (var j = 0; j !== bodies.length; j++) {
  73177. var b = bodies[j];
  73178. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  73179. b.position.vsub(b.previousPosition, interpvelo);
  73180. interpvelo.scale(h_div_dt, interpvelo);
  73181. b.position.vadd(interpvelo, b.interpolatedPosition);
  73182. }
  73183. else {
  73184. b.interpolatedPosition.copy(b.position);
  73185. b.interpolatedQuaternion.copy(b.quaternion);
  73186. }
  73187. }
  73188. }
  73189. };
  73190. };
  73191. return CannonJSPlugin;
  73192. }());
  73193. BABYLON.CannonJSPlugin = CannonJSPlugin;
  73194. })(BABYLON || (BABYLON = {}));
  73195. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  73196. var BABYLON;
  73197. (function (BABYLON) {
  73198. var OimoJSPlugin = /** @class */ (function () {
  73199. function OimoJSPlugin(iterations) {
  73200. this.name = "OimoJSPlugin";
  73201. this._tmpImpostorsArray = [];
  73202. this._tmpPositionVector = BABYLON.Vector3.Zero();
  73203. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  73204. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  73205. this.world.worldscale(1);
  73206. this.world.clear();
  73207. //making sure no stats are calculated
  73208. this.world.isNoStat = true;
  73209. }
  73210. OimoJSPlugin.prototype.setGravity = function (gravity) {
  73211. this.world.gravity.copy(gravity);
  73212. };
  73213. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  73214. this.world.timeStep = timeStep;
  73215. };
  73216. OimoJSPlugin.prototype.getTimeStep = function () {
  73217. return this.world.timeStep;
  73218. };
  73219. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  73220. var _this = this;
  73221. impostors.forEach(function (impostor) {
  73222. impostor.beforeStep();
  73223. });
  73224. this.world.step();
  73225. impostors.forEach(function (impostor) {
  73226. impostor.afterStep();
  73227. //update the ordered impostors array
  73228. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  73229. });
  73230. //check for collisions
  73231. var contact = this.world.contacts;
  73232. while (contact !== null) {
  73233. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  73234. contact = contact.next;
  73235. continue;
  73236. }
  73237. //is this body colliding with any other? get the impostor
  73238. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  73239. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  73240. if (!mainImpostor || !collidingImpostor) {
  73241. contact = contact.next;
  73242. continue;
  73243. }
  73244. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  73245. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  73246. contact = contact.next;
  73247. }
  73248. };
  73249. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  73250. var mass = impostor.physicsBody.massInfo.mass;
  73251. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  73252. };
  73253. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  73254. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  73255. this.applyImpulse(impostor, force, contactPoint);
  73256. };
  73257. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  73258. var _this = this;
  73259. //parent-child relationship. Does this impostor has a parent impostor?
  73260. if (impostor.parent) {
  73261. if (impostor.physicsBody) {
  73262. this.removePhysicsBody(impostor);
  73263. //TODO is that needed?
  73264. impostor.forceUpdate();
  73265. }
  73266. return;
  73267. }
  73268. if (impostor.isBodyInitRequired()) {
  73269. var bodyConfig = {
  73270. name: impostor.uniqueId,
  73271. //Oimo must have mass, also for static objects.
  73272. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  73273. size: [],
  73274. type: [],
  73275. pos: [],
  73276. rot: [],
  73277. move: impostor.getParam("mass") !== 0,
  73278. //Supporting older versions of Oimo
  73279. world: this.world
  73280. };
  73281. var impostors = [impostor];
  73282. var addToArray = function (parent) {
  73283. if (!parent.getChildMeshes)
  73284. return;
  73285. parent.getChildMeshes().forEach(function (m) {
  73286. if (m.physicsImpostor) {
  73287. impostors.push(m.physicsImpostor);
  73288. //m.physicsImpostor._init();
  73289. }
  73290. });
  73291. };
  73292. addToArray(impostor.object);
  73293. var checkWithEpsilon_1 = function (value) {
  73294. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  73295. };
  73296. impostors.forEach(function (i) {
  73297. if (!impostor.object.rotationQuaternion) {
  73298. return;
  73299. }
  73300. //get the correct bounding box
  73301. var oldQuaternion = i.object.rotationQuaternion;
  73302. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  73303. x: impostor.object.rotationQuaternion.x,
  73304. y: impostor.object.rotationQuaternion.y,
  73305. z: impostor.object.rotationQuaternion.z,
  73306. s: impostor.object.rotationQuaternion.w
  73307. });
  73308. var extendSize = i.getObjectExtendSize();
  73309. if (i === impostor) {
  73310. var center = impostor.getObjectCenter();
  73311. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  73312. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  73313. //Can also use Array.prototype.push.apply
  73314. bodyConfig.pos.push(center.x);
  73315. bodyConfig.pos.push(center.y);
  73316. bodyConfig.pos.push(center.z);
  73317. //tmp solution
  73318. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73319. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73320. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73321. }
  73322. else {
  73323. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  73324. bodyConfig.pos.push(localPosition.x);
  73325. bodyConfig.pos.push(localPosition.y);
  73326. bodyConfig.pos.push(localPosition.z);
  73327. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  73328. bodyConfig.rot.push(0);
  73329. bodyConfig.rot.push(0);
  73330. bodyConfig.rot.push(0);
  73331. }
  73332. // register mesh
  73333. switch (i.type) {
  73334. case BABYLON.PhysicsImpostor.ParticleImpostor:
  73335. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  73336. case BABYLON.PhysicsImpostor.SphereImpostor:
  73337. var radiusX = extendSize.x;
  73338. var radiusY = extendSize.y;
  73339. var radiusZ = extendSize.z;
  73340. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  73341. bodyConfig.type.push('sphere');
  73342. //due to the way oimo works with compounds, add 3 times
  73343. bodyConfig.size.push(size);
  73344. bodyConfig.size.push(size);
  73345. bodyConfig.size.push(size);
  73346. break;
  73347. case BABYLON.PhysicsImpostor.CylinderImpostor:
  73348. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  73349. var sizeY = checkWithEpsilon_1(extendSize.y);
  73350. bodyConfig.type.push('cylinder');
  73351. bodyConfig.size.push(sizeX);
  73352. bodyConfig.size.push(sizeY);
  73353. //due to the way oimo works with compounds, add one more value.
  73354. bodyConfig.size.push(sizeY);
  73355. break;
  73356. case BABYLON.PhysicsImpostor.PlaneImpostor:
  73357. case BABYLON.PhysicsImpostor.BoxImpostor:
  73358. default:
  73359. var sizeX = checkWithEpsilon_1(extendSize.x);
  73360. var sizeY = checkWithEpsilon_1(extendSize.y);
  73361. var sizeZ = checkWithEpsilon_1(extendSize.z);
  73362. bodyConfig.type.push('box');
  73363. bodyConfig.size.push(sizeX);
  73364. bodyConfig.size.push(sizeY);
  73365. bodyConfig.size.push(sizeZ);
  73366. break;
  73367. }
  73368. //actually not needed, but hey...
  73369. i.object.rotationQuaternion = oldQuaternion;
  73370. });
  73371. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  73372. }
  73373. else {
  73374. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  73375. }
  73376. impostor.setDeltaPosition(this._tmpPositionVector);
  73377. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  73378. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  73379. };
  73380. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  73381. //impostor.physicsBody.dispose();
  73382. //Same as : (older oimo versions)
  73383. this.world.removeRigidBody(impostor.physicsBody);
  73384. };
  73385. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  73386. var mainBody = impostorJoint.mainImpostor.physicsBody;
  73387. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  73388. if (!mainBody || !connectedBody) {
  73389. return;
  73390. }
  73391. var jointData = impostorJoint.joint.jointData;
  73392. var options = jointData.nativeParams || {};
  73393. var type;
  73394. var nativeJointData = {
  73395. body1: mainBody,
  73396. body2: connectedBody,
  73397. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  73398. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  73399. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  73400. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  73401. min: options.min,
  73402. max: options.max,
  73403. collision: options.collision || jointData.collision,
  73404. spring: options.spring,
  73405. //supporting older version of Oimo
  73406. world: this.world
  73407. };
  73408. switch (impostorJoint.joint.type) {
  73409. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  73410. type = "jointBall";
  73411. break;
  73412. case BABYLON.PhysicsJoint.SpringJoint:
  73413. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  73414. var springData = jointData;
  73415. nativeJointData.min = springData.length || nativeJointData.min;
  73416. //Max should also be set, just make sure it is at least min
  73417. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  73418. case BABYLON.PhysicsJoint.DistanceJoint:
  73419. type = "jointDistance";
  73420. nativeJointData.max = jointData.maxDistance;
  73421. break;
  73422. case BABYLON.PhysicsJoint.PrismaticJoint:
  73423. type = "jointPrisme";
  73424. break;
  73425. case BABYLON.PhysicsJoint.SliderJoint:
  73426. type = "jointSlide";
  73427. break;
  73428. case BABYLON.PhysicsJoint.WheelJoint:
  73429. type = "jointWheel";
  73430. break;
  73431. case BABYLON.PhysicsJoint.HingeJoint:
  73432. default:
  73433. type = "jointHinge";
  73434. break;
  73435. }
  73436. nativeJointData.type = type;
  73437. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  73438. };
  73439. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  73440. //Bug in Oimo prevents us from disposing a joint in the playground
  73441. //joint.joint.physicsJoint.dispose();
  73442. //So we will bruteforce it!
  73443. try {
  73444. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  73445. }
  73446. catch (e) {
  73447. BABYLON.Tools.Warn(e);
  73448. }
  73449. };
  73450. OimoJSPlugin.prototype.isSupported = function () {
  73451. return this.BJSOIMO !== undefined;
  73452. };
  73453. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73454. if (!impostor.physicsBody.sleeping) {
  73455. //TODO check that
  73456. if (impostor.physicsBody.shapes.next) {
  73457. var parentShape = this._getLastShape(impostor.physicsBody);
  73458. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  73459. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  73460. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  73461. }
  73462. else {
  73463. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  73464. }
  73465. if (impostor.object.rotationQuaternion) {
  73466. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  73467. impostor.object.rotationQuaternion.normalize();
  73468. }
  73469. }
  73470. };
  73471. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73472. var body = impostor.physicsBody;
  73473. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  73474. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  73475. body.syncShapes();
  73476. body.awake();
  73477. };
  73478. OimoJSPlugin.prototype._getLastShape = function (body) {
  73479. var lastShape = body.shapes;
  73480. while (lastShape.next) {
  73481. lastShape = lastShape.next;
  73482. }
  73483. return lastShape;
  73484. };
  73485. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73486. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  73487. };
  73488. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73489. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  73490. };
  73491. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73492. var v = impostor.physicsBody.linearVelocity;
  73493. if (!v) {
  73494. return null;
  73495. }
  73496. return new BABYLON.Vector3(v.x, v.y, v.z);
  73497. };
  73498. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73499. var v = impostor.physicsBody.angularVelocity;
  73500. if (!v) {
  73501. return null;
  73502. }
  73503. return new BABYLON.Vector3(v.x, v.y, v.z);
  73504. };
  73505. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73506. var staticBody = mass === 0;
  73507. //this will actually set the body's density and not its mass.
  73508. //But this is how oimo treats the mass variable.
  73509. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  73510. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  73511. };
  73512. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  73513. return impostor.physicsBody.shapes.density;
  73514. };
  73515. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  73516. return impostor.physicsBody.shapes.friction;
  73517. };
  73518. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73519. impostor.physicsBody.shapes.friction = friction;
  73520. };
  73521. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73522. return impostor.physicsBody.shapes.restitution;
  73523. };
  73524. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73525. impostor.physicsBody.shapes.restitution = restitution;
  73526. };
  73527. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  73528. impostor.physicsBody.sleep();
  73529. };
  73530. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  73531. impostor.physicsBody.awake();
  73532. };
  73533. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73534. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  73535. if (minDistance !== void 0) {
  73536. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  73537. }
  73538. };
  73539. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73540. //TODO separate rotational and transational motors.
  73541. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73542. if (motor) {
  73543. motor.setMotor(speed, maxForce);
  73544. }
  73545. };
  73546. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  73547. //TODO separate rotational and transational motors.
  73548. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73549. if (motor) {
  73550. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  73551. }
  73552. };
  73553. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73554. var body = impostor.physicsBody;
  73555. mesh.position.x = body.position.x;
  73556. mesh.position.y = body.position.y;
  73557. mesh.position.z = body.position.z;
  73558. if (mesh.rotationQuaternion) {
  73559. mesh.rotationQuaternion.x = body.orientation.x;
  73560. mesh.rotationQuaternion.y = body.orientation.y;
  73561. mesh.rotationQuaternion.z = body.orientation.z;
  73562. mesh.rotationQuaternion.w = body.orientation.s;
  73563. }
  73564. };
  73565. OimoJSPlugin.prototype.getRadius = function (impostor) {
  73566. return impostor.physicsBody.shapes.radius;
  73567. };
  73568. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73569. var shape = impostor.physicsBody.shapes;
  73570. result.x = shape.halfWidth * 2;
  73571. result.y = shape.halfHeight * 2;
  73572. result.z = shape.halfDepth * 2;
  73573. };
  73574. OimoJSPlugin.prototype.dispose = function () {
  73575. this.world.clear();
  73576. };
  73577. return OimoJSPlugin;
  73578. }());
  73579. BABYLON.OimoJSPlugin = OimoJSPlugin;
  73580. })(BABYLON || (BABYLON = {}));
  73581. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  73582. var BABYLON;
  73583. (function (BABYLON) {
  73584. /*
  73585. * Based on jsTGALoader - Javascript loader for TGA file
  73586. * By Vincent Thibault
  73587. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  73588. */
  73589. var TGATools = /** @class */ (function () {
  73590. function TGATools() {
  73591. }
  73592. TGATools.GetTGAHeader = function (data) {
  73593. var offset = 0;
  73594. var header = {
  73595. id_length: data[offset++],
  73596. colormap_type: data[offset++],
  73597. image_type: data[offset++],
  73598. colormap_index: data[offset++] | data[offset++] << 8,
  73599. colormap_length: data[offset++] | data[offset++] << 8,
  73600. colormap_size: data[offset++],
  73601. origin: [
  73602. data[offset++] | data[offset++] << 8,
  73603. data[offset++] | data[offset++] << 8
  73604. ],
  73605. width: data[offset++] | data[offset++] << 8,
  73606. height: data[offset++] | data[offset++] << 8,
  73607. pixel_size: data[offset++],
  73608. flags: data[offset++]
  73609. };
  73610. return header;
  73611. };
  73612. TGATools.UploadContent = function (gl, data) {
  73613. // Not enough data to contain header ?
  73614. if (data.length < 19) {
  73615. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  73616. return;
  73617. }
  73618. // Read Header
  73619. var offset = 18;
  73620. var header = TGATools.GetTGAHeader(data);
  73621. // Assume it's a valid Targa file.
  73622. if (header.id_length + offset > data.length) {
  73623. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  73624. return;
  73625. }
  73626. // Skip not needed data
  73627. offset += header.id_length;
  73628. var use_rle = false;
  73629. var use_pal = false;
  73630. var use_grey = false;
  73631. // Get some informations.
  73632. switch (header.image_type) {
  73633. case TGATools._TYPE_RLE_INDEXED:
  73634. use_rle = true;
  73635. case TGATools._TYPE_INDEXED:
  73636. use_pal = true;
  73637. break;
  73638. case TGATools._TYPE_RLE_RGB:
  73639. use_rle = true;
  73640. case TGATools._TYPE_RGB:
  73641. // use_rgb = true;
  73642. break;
  73643. case TGATools._TYPE_RLE_GREY:
  73644. use_rle = true;
  73645. case TGATools._TYPE_GREY:
  73646. use_grey = true;
  73647. break;
  73648. }
  73649. var pixel_data;
  73650. // var numAlphaBits = header.flags & 0xf;
  73651. var pixel_size = header.pixel_size >> 3;
  73652. var pixel_total = header.width * header.height * pixel_size;
  73653. // Read palettes
  73654. var palettes;
  73655. if (use_pal) {
  73656. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  73657. }
  73658. // Read LRE
  73659. if (use_rle) {
  73660. pixel_data = new Uint8Array(pixel_total);
  73661. var c, count, i;
  73662. var localOffset = 0;
  73663. var pixels = new Uint8Array(pixel_size);
  73664. while (offset < pixel_total && localOffset < pixel_total) {
  73665. c = data[offset++];
  73666. count = (c & 0x7f) + 1;
  73667. // RLE pixels
  73668. if (c & 0x80) {
  73669. // Bind pixel tmp array
  73670. for (i = 0; i < pixel_size; ++i) {
  73671. pixels[i] = data[offset++];
  73672. }
  73673. // Copy pixel array
  73674. for (i = 0; i < count; ++i) {
  73675. pixel_data.set(pixels, localOffset + i * pixel_size);
  73676. }
  73677. localOffset += pixel_size * count;
  73678. }
  73679. else {
  73680. count *= pixel_size;
  73681. for (i = 0; i < count; ++i) {
  73682. pixel_data[localOffset + i] = data[offset++];
  73683. }
  73684. localOffset += count;
  73685. }
  73686. }
  73687. }
  73688. else {
  73689. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  73690. }
  73691. // Load to texture
  73692. var x_start, y_start, x_step, y_step, y_end, x_end;
  73693. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  73694. default:
  73695. case TGATools._ORIGIN_UL:
  73696. x_start = 0;
  73697. x_step = 1;
  73698. x_end = header.width;
  73699. y_start = 0;
  73700. y_step = 1;
  73701. y_end = header.height;
  73702. break;
  73703. case TGATools._ORIGIN_BL:
  73704. x_start = 0;
  73705. x_step = 1;
  73706. x_end = header.width;
  73707. y_start = header.height - 1;
  73708. y_step = -1;
  73709. y_end = -1;
  73710. break;
  73711. case TGATools._ORIGIN_UR:
  73712. x_start = header.width - 1;
  73713. x_step = -1;
  73714. x_end = -1;
  73715. y_start = 0;
  73716. y_step = 1;
  73717. y_end = header.height;
  73718. break;
  73719. case TGATools._ORIGIN_BR:
  73720. x_start = header.width - 1;
  73721. x_step = -1;
  73722. x_end = -1;
  73723. y_start = header.height - 1;
  73724. y_step = -1;
  73725. y_end = -1;
  73726. break;
  73727. }
  73728. // Load the specify method
  73729. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  73730. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  73731. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  73732. };
  73733. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73734. var image = pixel_data, colormap = palettes;
  73735. var width = header.width, height = header.height;
  73736. var color, i = 0, x, y;
  73737. var imageData = new Uint8Array(width * height * 4);
  73738. for (y = y_start; y !== y_end; y += y_step) {
  73739. for (x = x_start; x !== x_end; x += x_step, i++) {
  73740. color = image[i];
  73741. imageData[(x + width * y) * 4 + 3] = 255;
  73742. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  73743. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  73744. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  73745. }
  73746. }
  73747. return imageData;
  73748. };
  73749. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73750. var image = pixel_data;
  73751. var width = header.width, height = header.height;
  73752. var color, i = 0, x, y;
  73753. var imageData = new Uint8Array(width * height * 4);
  73754. for (y = y_start; y !== y_end; y += y_step) {
  73755. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73756. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  73757. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  73758. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  73759. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  73760. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  73761. }
  73762. }
  73763. return imageData;
  73764. };
  73765. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73766. var image = pixel_data;
  73767. var width = header.width, height = header.height;
  73768. var i = 0, x, y;
  73769. var imageData = new Uint8Array(width * height * 4);
  73770. for (y = y_start; y !== y_end; y += y_step) {
  73771. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  73772. imageData[(x + width * y) * 4 + 3] = 255;
  73773. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73774. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73775. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73776. }
  73777. }
  73778. return imageData;
  73779. };
  73780. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73781. var image = pixel_data;
  73782. var width = header.width, height = header.height;
  73783. var i = 0, x, y;
  73784. var imageData = new Uint8Array(width * height * 4);
  73785. for (y = y_start; y !== y_end; y += y_step) {
  73786. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  73787. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73788. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73789. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73790. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  73791. }
  73792. }
  73793. return imageData;
  73794. };
  73795. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73796. var image = pixel_data;
  73797. var width = header.width, height = header.height;
  73798. var color, i = 0, x, y;
  73799. var imageData = new Uint8Array(width * height * 4);
  73800. for (y = y_start; y !== y_end; y += y_step) {
  73801. for (x = x_start; x !== x_end; x += x_step, i++) {
  73802. color = image[i];
  73803. imageData[(x + width * y) * 4 + 0] = color;
  73804. imageData[(x + width * y) * 4 + 1] = color;
  73805. imageData[(x + width * y) * 4 + 2] = color;
  73806. imageData[(x + width * y) * 4 + 3] = 255;
  73807. }
  73808. }
  73809. return imageData;
  73810. };
  73811. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73812. var image = pixel_data;
  73813. var width = header.width, height = header.height;
  73814. var i = 0, x, y;
  73815. var imageData = new Uint8Array(width * height * 4);
  73816. for (y = y_start; y !== y_end; y += y_step) {
  73817. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73818. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  73819. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  73820. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73821. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  73822. }
  73823. }
  73824. return imageData;
  73825. };
  73826. //private static _TYPE_NO_DATA = 0;
  73827. TGATools._TYPE_INDEXED = 1;
  73828. TGATools._TYPE_RGB = 2;
  73829. TGATools._TYPE_GREY = 3;
  73830. TGATools._TYPE_RLE_INDEXED = 9;
  73831. TGATools._TYPE_RLE_RGB = 10;
  73832. TGATools._TYPE_RLE_GREY = 11;
  73833. TGATools._ORIGIN_MASK = 0x30;
  73834. TGATools._ORIGIN_SHIFT = 0x04;
  73835. TGATools._ORIGIN_BL = 0x00;
  73836. TGATools._ORIGIN_BR = 0x01;
  73837. TGATools._ORIGIN_UL = 0x02;
  73838. TGATools._ORIGIN_UR = 0x03;
  73839. return TGATools;
  73840. }());
  73841. BABYLON.TGATools = TGATools;
  73842. })(BABYLON || (BABYLON = {}));
  73843. //# sourceMappingURL=babylon.tga.js.map
  73844. var BABYLON;
  73845. (function (BABYLON) {
  73846. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  73847. // All values and structures referenced from:
  73848. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  73849. var DDS_MAGIC = 0x20534444;
  73850. var
  73851. //DDSD_CAPS = 0x1,
  73852. //DDSD_HEIGHT = 0x2,
  73853. //DDSD_WIDTH = 0x4,
  73854. //DDSD_PITCH = 0x8,
  73855. //DDSD_PIXELFORMAT = 0x1000,
  73856. DDSD_MIPMAPCOUNT = 0x20000;
  73857. //DDSD_LINEARSIZE = 0x80000,
  73858. //DDSD_DEPTH = 0x800000;
  73859. // var DDSCAPS_COMPLEX = 0x8,
  73860. // DDSCAPS_MIPMAP = 0x400000,
  73861. // DDSCAPS_TEXTURE = 0x1000;
  73862. var DDSCAPS2_CUBEMAP = 0x200;
  73863. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  73864. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  73865. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  73866. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  73867. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  73868. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  73869. // DDSCAPS2_VOLUME = 0x200000;
  73870. var
  73871. //DDPF_ALPHAPIXELS = 0x1,
  73872. //DDPF_ALPHA = 0x2,
  73873. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  73874. //DDPF_YUV = 0x200,
  73875. DDPF_LUMINANCE = 0x20000;
  73876. function FourCCToInt32(value) {
  73877. return value.charCodeAt(0) +
  73878. (value.charCodeAt(1) << 8) +
  73879. (value.charCodeAt(2) << 16) +
  73880. (value.charCodeAt(3) << 24);
  73881. }
  73882. function Int32ToFourCC(value) {
  73883. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  73884. }
  73885. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  73886. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  73887. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  73888. var FOURCC_DX10 = FourCCToInt32("DX10");
  73889. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  73890. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  73891. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  73892. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  73893. var headerLengthInt = 31; // The header length in 32 bit ints
  73894. // Offsets into the header array
  73895. var off_magic = 0;
  73896. var off_size = 1;
  73897. var off_flags = 2;
  73898. var off_height = 3;
  73899. var off_width = 4;
  73900. var off_mipmapCount = 7;
  73901. var off_pfFlags = 20;
  73902. var off_pfFourCC = 21;
  73903. var off_RGBbpp = 22;
  73904. var off_RMask = 23;
  73905. var off_GMask = 24;
  73906. var off_BMask = 25;
  73907. var off_AMask = 26;
  73908. // var off_caps1 = 27;
  73909. var off_caps2 = 28;
  73910. // var off_caps3 = 29;
  73911. // var off_caps4 = 30;
  73912. var off_dxgiFormat = 32;
  73913. ;
  73914. var DDSTools = /** @class */ (function () {
  73915. function DDSTools() {
  73916. }
  73917. DDSTools.GetDDSInfo = function (arrayBuffer) {
  73918. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73919. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  73920. var mipmapCount = 1;
  73921. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  73922. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73923. }
  73924. var fourCC = header[off_pfFourCC];
  73925. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  73926. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73927. switch (fourCC) {
  73928. case FOURCC_D3DFMT_R16G16B16A16F:
  73929. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73930. break;
  73931. case FOURCC_D3DFMT_R32G32B32A32F:
  73932. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73933. break;
  73934. case FOURCC_DX10:
  73935. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  73936. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73937. break;
  73938. }
  73939. }
  73940. return {
  73941. width: header[off_width],
  73942. height: header[off_height],
  73943. mipmapCount: mipmapCount,
  73944. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  73945. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  73946. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  73947. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  73948. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  73949. dxgiFormat: dxgiFormat,
  73950. textureType: textureType
  73951. };
  73952. };
  73953. DDSTools._ToHalfFloat = function (value) {
  73954. if (!DDSTools._FloatView) {
  73955. DDSTools._FloatView = new Float32Array(1);
  73956. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  73957. }
  73958. DDSTools._FloatView[0] = value;
  73959. var x = DDSTools._Int32View[0];
  73960. var bits = (x >> 16) & 0x8000; /* Get the sign */
  73961. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  73962. var e = (x >> 23) & 0xff; /* Using int is faster here */
  73963. /* If zero, or denormal, or exponent underflows too much for a denormal
  73964. * half, return signed zero. */
  73965. if (e < 103) {
  73966. return bits;
  73967. }
  73968. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  73969. if (e > 142) {
  73970. bits |= 0x7c00;
  73971. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  73972. * not Inf, so make sure we set one mantissa bit too. */
  73973. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  73974. return bits;
  73975. }
  73976. /* If exponent underflows but not too much, return a denormal */
  73977. if (e < 113) {
  73978. m |= 0x0800;
  73979. /* Extra rounding may overflow and set mantissa to 0 and exponent
  73980. * to 1, which is OK. */
  73981. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  73982. return bits;
  73983. }
  73984. bits |= ((e - 112) << 10) | (m >> 1);
  73985. bits += m & 1;
  73986. return bits;
  73987. };
  73988. DDSTools._FromHalfFloat = function (value) {
  73989. var s = (value & 0x8000) >> 15;
  73990. var e = (value & 0x7C00) >> 10;
  73991. var f = value & 0x03FF;
  73992. if (e === 0) {
  73993. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  73994. }
  73995. else if (e == 0x1F) {
  73996. return f ? NaN : ((s ? -1 : 1) * Infinity);
  73997. }
  73998. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  73999. };
  74000. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74001. var destArray = new Float32Array(dataLength);
  74002. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74003. var index = 0;
  74004. for (var y = 0; y < height; y++) {
  74005. for (var x = 0; x < width; x++) {
  74006. var srcPos = (x + y * width) * 4;
  74007. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  74008. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  74009. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  74010. if (DDSTools.StoreLODInAlphaChannel) {
  74011. destArray[index + 3] = lod;
  74012. }
  74013. else {
  74014. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  74015. }
  74016. index += 4;
  74017. }
  74018. }
  74019. return destArray;
  74020. };
  74021. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74022. if (DDSTools.StoreLODInAlphaChannel) {
  74023. var destArray = new Uint16Array(dataLength);
  74024. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74025. var index = 0;
  74026. for (var y = 0; y < height; y++) {
  74027. for (var x = 0; x < width; x++) {
  74028. var srcPos = (x + y * width) * 4;
  74029. destArray[index] = srcData[srcPos];
  74030. destArray[index + 1] = srcData[srcPos + 1];
  74031. destArray[index + 2] = srcData[srcPos + 2];
  74032. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  74033. index += 4;
  74034. }
  74035. }
  74036. return destArray;
  74037. }
  74038. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  74039. };
  74040. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74041. if (DDSTools.StoreLODInAlphaChannel) {
  74042. var destArray = new Float32Array(dataLength);
  74043. var srcData = new Float32Array(arrayBuffer, dataOffset);
  74044. var index = 0;
  74045. for (var y = 0; y < height; y++) {
  74046. for (var x = 0; x < width; x++) {
  74047. var srcPos = (x + y * width) * 4;
  74048. destArray[index] = srcData[srcPos];
  74049. destArray[index + 1] = srcData[srcPos + 1];
  74050. destArray[index + 2] = srcData[srcPos + 2];
  74051. destArray[index + 3] = lod;
  74052. index += 4;
  74053. }
  74054. }
  74055. return destArray;
  74056. }
  74057. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  74058. };
  74059. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74060. var destArray = new Uint8Array(dataLength);
  74061. var srcData = new Float32Array(arrayBuffer, dataOffset);
  74062. var index = 0;
  74063. for (var y = 0; y < height; y++) {
  74064. for (var x = 0; x < width; x++) {
  74065. var srcPos = (x + y * width) * 4;
  74066. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  74067. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  74068. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  74069. if (DDSTools.StoreLODInAlphaChannel) {
  74070. destArray[index + 3] = lod;
  74071. }
  74072. else {
  74073. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  74074. }
  74075. index += 4;
  74076. }
  74077. }
  74078. return destArray;
  74079. };
  74080. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74081. var destArray = new Uint8Array(dataLength);
  74082. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74083. var index = 0;
  74084. for (var y = 0; y < height; y++) {
  74085. for (var x = 0; x < width; x++) {
  74086. var srcPos = (x + y * width) * 4;
  74087. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  74088. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  74089. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  74090. if (DDSTools.StoreLODInAlphaChannel) {
  74091. destArray[index + 3] = lod;
  74092. }
  74093. else {
  74094. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  74095. }
  74096. index += 4;
  74097. }
  74098. }
  74099. return destArray;
  74100. };
  74101. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  74102. var byteArray = new Uint8Array(dataLength);
  74103. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74104. var index = 0;
  74105. for (var y = 0; y < height; y++) {
  74106. for (var x = 0; x < width; x++) {
  74107. var srcPos = (x + y * width) * 4;
  74108. byteArray[index] = srcData[srcPos + rOffset];
  74109. byteArray[index + 1] = srcData[srcPos + gOffset];
  74110. byteArray[index + 2] = srcData[srcPos + bOffset];
  74111. byteArray[index + 3] = srcData[srcPos + aOffset];
  74112. index += 4;
  74113. }
  74114. }
  74115. return byteArray;
  74116. };
  74117. DDSTools._ExtractLongWordOrder = function (value) {
  74118. if (value === 0 || value === 255 || value === -16777216) {
  74119. return 0;
  74120. }
  74121. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  74122. };
  74123. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  74124. var byteArray = new Uint8Array(dataLength);
  74125. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74126. var index = 0;
  74127. for (var y = 0; y < height; y++) {
  74128. for (var x = 0; x < width; x++) {
  74129. var srcPos = (x + y * width) * 3;
  74130. byteArray[index] = srcData[srcPos + rOffset];
  74131. byteArray[index + 1] = srcData[srcPos + gOffset];
  74132. byteArray[index + 2] = srcData[srcPos + bOffset];
  74133. index += 3;
  74134. }
  74135. }
  74136. return byteArray;
  74137. };
  74138. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  74139. var byteArray = new Uint8Array(dataLength);
  74140. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74141. var index = 0;
  74142. for (var y = 0; y < height; y++) {
  74143. for (var x = 0; x < width; x++) {
  74144. var srcPos = (x + y * width);
  74145. byteArray[index] = srcData[srcPos];
  74146. index++;
  74147. }
  74148. }
  74149. return byteArray;
  74150. };
  74151. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  74152. if (lodIndex === void 0) { lodIndex = -1; }
  74153. var ext = engine.getCaps().s3tc;
  74154. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  74155. var fourCC, width, height, dataLength = 0, dataOffset;
  74156. var byteArray, mipmapCount, mip;
  74157. var internalFormat = 0;
  74158. var format = 0;
  74159. var blockBytes = 1;
  74160. if (header[off_magic] !== DDS_MAGIC) {
  74161. BABYLON.Tools.Error("Invalid magic number in DDS header");
  74162. return;
  74163. }
  74164. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  74165. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  74166. return;
  74167. }
  74168. if (info.isCompressed && !ext) {
  74169. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  74170. return;
  74171. }
  74172. var bpp = header[off_RGBbpp];
  74173. dataOffset = header[off_size] + 4;
  74174. var computeFormats = false;
  74175. if (info.isFourCC) {
  74176. fourCC = header[off_pfFourCC];
  74177. switch (fourCC) {
  74178. case FOURCC_DXT1:
  74179. blockBytes = 8;
  74180. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  74181. break;
  74182. case FOURCC_DXT3:
  74183. blockBytes = 16;
  74184. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  74185. break;
  74186. case FOURCC_DXT5:
  74187. blockBytes = 16;
  74188. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  74189. break;
  74190. case FOURCC_D3DFMT_R16G16B16A16F:
  74191. computeFormats = true;
  74192. break;
  74193. case FOURCC_D3DFMT_R32G32B32A32F:
  74194. computeFormats = true;
  74195. break;
  74196. case FOURCC_DX10:
  74197. // There is an additionnal header so dataOffset need to be changed
  74198. dataOffset += 5 * 4; // 5 uints
  74199. var supported = false;
  74200. switch (info.dxgiFormat) {
  74201. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  74202. computeFormats = true;
  74203. supported = true;
  74204. break;
  74205. case DXGI_FORMAT_B8G8R8X8_UNORM:
  74206. info.isRGB = true;
  74207. info.isFourCC = false;
  74208. bpp = 32;
  74209. supported = true;
  74210. break;
  74211. }
  74212. if (supported) {
  74213. break;
  74214. }
  74215. default:
  74216. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  74217. return;
  74218. }
  74219. }
  74220. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  74221. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  74222. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  74223. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  74224. if (computeFormats) {
  74225. format = engine._getWebGLTextureType(info.textureType);
  74226. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74227. }
  74228. mipmapCount = 1;
  74229. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  74230. mipmapCount = Math.max(1, header[off_mipmapCount]);
  74231. }
  74232. for (var face = 0; face < faces; face++) {
  74233. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  74234. width = header[off_width];
  74235. height = header[off_height];
  74236. for (mip = 0; mip < mipmapCount; ++mip) {
  74237. if (lodIndex === -1 || lodIndex === mip) {
  74238. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  74239. var i = (lodIndex === -1) ? mip : 0;
  74240. if (!info.isCompressed && info.isFourCC) {
  74241. dataLength = width * height * 4;
  74242. var floatArray = null;
  74243. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  74244. if (bpp === 128) {
  74245. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74246. }
  74247. else if (bpp === 64) {
  74248. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74249. }
  74250. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74251. format = engine._getWebGLTextureType(info.textureType);
  74252. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74253. }
  74254. else {
  74255. if (bpp === 128) {
  74256. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74257. }
  74258. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  74259. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74260. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74261. format = engine._getWebGLTextureType(info.textureType);
  74262. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74263. }
  74264. else {
  74265. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74266. }
  74267. }
  74268. if (floatArray) {
  74269. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  74270. }
  74271. }
  74272. else if (info.isRGB) {
  74273. if (bpp === 24) {
  74274. dataLength = width * height * 3;
  74275. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  74276. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  74277. }
  74278. else {
  74279. dataLength = width * height * 4;
  74280. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  74281. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  74282. }
  74283. }
  74284. else if (info.isLuminance) {
  74285. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  74286. var unpaddedRowSize = width;
  74287. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  74288. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  74289. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  74290. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  74291. }
  74292. else {
  74293. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  74294. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  74295. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  74296. }
  74297. }
  74298. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  74299. width *= 0.5;
  74300. height *= 0.5;
  74301. width = Math.max(1.0, width);
  74302. height = Math.max(1.0, height);
  74303. }
  74304. if (currentFace !== undefined) {
  74305. // Loading a single face
  74306. break;
  74307. }
  74308. }
  74309. };
  74310. DDSTools.StoreLODInAlphaChannel = false;
  74311. return DDSTools;
  74312. }());
  74313. BABYLON.DDSTools = DDSTools;
  74314. })(BABYLON || (BABYLON = {}));
  74315. //# sourceMappingURL=babylon.dds.js.map
  74316. var BABYLON;
  74317. (function (BABYLON) {
  74318. /**
  74319. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  74320. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  74321. */
  74322. var KhronosTextureContainer = /** @class */ (function () {
  74323. /**
  74324. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  74325. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  74326. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  74327. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  74328. */
  74329. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  74330. this.arrayBuffer = arrayBuffer;
  74331. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  74332. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  74333. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  74334. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  74335. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  74336. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  74337. BABYLON.Tools.Error("texture missing KTX identifier");
  74338. return;
  74339. }
  74340. // load the reset of the header in native 32 bit int
  74341. var header = new Int32Array(this.arrayBuffer, 12, 13);
  74342. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  74343. var oppositeEndianess = header[0] === 0x01020304;
  74344. // read all the header elements in order they exist in the file, without modification (sans endainness)
  74345. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  74346. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  74347. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  74348. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  74349. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  74350. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  74351. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  74352. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  74353. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  74354. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  74355. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  74356. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  74357. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  74358. if (this.glType !== 0) {
  74359. BABYLON.Tools.Error("only compressed formats currently supported");
  74360. return;
  74361. }
  74362. else {
  74363. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  74364. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  74365. }
  74366. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  74367. BABYLON.Tools.Error("only 2D textures currently supported");
  74368. return;
  74369. }
  74370. if (this.numberOfArrayElements !== 0) {
  74371. BABYLON.Tools.Error("texture arrays not currently supported");
  74372. return;
  74373. }
  74374. if (this.numberOfFaces !== facesExpected) {
  74375. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  74376. return;
  74377. }
  74378. // we now have a completely validated file, so could use existence of loadType as success
  74379. // would need to make this more elaborate & adjust checks above to support more than one load type
  74380. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  74381. }
  74382. // not as fast hardware based, but will probably never need to use
  74383. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  74384. return ((val & 0xFF) << 24)
  74385. | ((val & 0xFF00) << 8)
  74386. | ((val >> 8) & 0xFF00)
  74387. | ((val >> 24) & 0xFF);
  74388. };
  74389. /**
  74390. * It is assumed that the texture has already been created & is currently bound
  74391. */
  74392. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  74393. switch (this.loadType) {
  74394. case KhronosTextureContainer.COMPRESSED_2D:
  74395. this._upload2DCompressedLevels(gl, loadMipmaps);
  74396. break;
  74397. case KhronosTextureContainer.TEX_2D:
  74398. case KhronosTextureContainer.COMPRESSED_3D:
  74399. case KhronosTextureContainer.TEX_3D:
  74400. }
  74401. };
  74402. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  74403. // initialize width & height for level 1
  74404. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  74405. var width = this.pixelWidth;
  74406. var height = this.pixelHeight;
  74407. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  74408. for (var level = 0; level < mipmapCount; level++) {
  74409. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  74410. for (var face = 0; face < this.numberOfFaces; face++) {
  74411. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  74412. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  74413. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  74414. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  74415. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  74416. }
  74417. width = Math.max(1.0, width * 0.5);
  74418. height = Math.max(1.0, height * 0.5);
  74419. }
  74420. };
  74421. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  74422. // load types
  74423. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  74424. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  74425. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  74426. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  74427. return KhronosTextureContainer;
  74428. }());
  74429. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  74430. })(BABYLON || (BABYLON = {}));
  74431. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  74432. var BABYLON;
  74433. (function (BABYLON) {
  74434. var Debug = /** @class */ (function () {
  74435. function Debug() {
  74436. }
  74437. Debug.AxesViewer = /** @class */ (function () {
  74438. function AxesViewer(scene, scaleLines) {
  74439. if (scaleLines === void 0) { scaleLines = 1; }
  74440. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74441. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74442. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74443. this.scaleLines = 1;
  74444. this.scaleLines = scaleLines;
  74445. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  74446. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  74447. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  74448. this._xmesh.renderingGroupId = 2;
  74449. this._ymesh.renderingGroupId = 2;
  74450. this._zmesh.renderingGroupId = 2;
  74451. this._xmesh.material.checkReadyOnlyOnce = true;
  74452. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  74453. this._ymesh.material.checkReadyOnlyOnce = true;
  74454. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  74455. this._zmesh.material.checkReadyOnlyOnce = true;
  74456. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  74457. this.scene = scene;
  74458. }
  74459. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  74460. var scaleLines = this.scaleLines;
  74461. if (this._xmesh) {
  74462. this._xmesh.position.copyFrom(position);
  74463. }
  74464. if (this._ymesh) {
  74465. this._ymesh.position.copyFrom(position);
  74466. }
  74467. if (this._zmesh) {
  74468. this._zmesh.position.copyFrom(position);
  74469. }
  74470. var point2 = this._xline[1];
  74471. point2.x = xaxis.x * scaleLines;
  74472. point2.y = xaxis.y * scaleLines;
  74473. point2.z = xaxis.z * scaleLines;
  74474. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  74475. point2 = this._yline[1];
  74476. point2.x = yaxis.x * scaleLines;
  74477. point2.y = yaxis.y * scaleLines;
  74478. point2.z = yaxis.z * scaleLines;
  74479. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  74480. point2 = this._zline[1];
  74481. point2.x = zaxis.x * scaleLines;
  74482. point2.y = zaxis.y * scaleLines;
  74483. point2.z = zaxis.z * scaleLines;
  74484. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  74485. };
  74486. AxesViewer.prototype.dispose = function () {
  74487. if (this._xmesh) {
  74488. this._xmesh.dispose();
  74489. }
  74490. if (this._ymesh) {
  74491. this._ymesh.dispose();
  74492. }
  74493. if (this._zmesh) {
  74494. this._zmesh.dispose();
  74495. }
  74496. this._xmesh = null;
  74497. this._ymesh = null;
  74498. this._zmesh = null;
  74499. this.scene = null;
  74500. };
  74501. return AxesViewer;
  74502. }());
  74503. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  74504. __extends(BoneAxesViewer, _super);
  74505. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  74506. if (scaleLines === void 0) { scaleLines = 1; }
  74507. var _this = _super.call(this, scene, scaleLines) || this;
  74508. _this.pos = BABYLON.Vector3.Zero();
  74509. _this.xaxis = BABYLON.Vector3.Zero();
  74510. _this.yaxis = BABYLON.Vector3.Zero();
  74511. _this.zaxis = BABYLON.Vector3.Zero();
  74512. _this.mesh = mesh;
  74513. _this.bone = bone;
  74514. return _this;
  74515. }
  74516. BoneAxesViewer.prototype.update = function () {
  74517. if (!this.mesh || !this.bone) {
  74518. return;
  74519. }
  74520. var bone = this.bone;
  74521. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  74522. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  74523. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  74524. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  74525. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  74526. };
  74527. BoneAxesViewer.prototype.dispose = function () {
  74528. if (this.mesh) {
  74529. this.mesh = null;
  74530. this.bone = null;
  74531. _super.prototype.dispose.call(this);
  74532. }
  74533. };
  74534. return BoneAxesViewer;
  74535. }(Debug.AxesViewer));
  74536. Debug.PhysicsViewer = /** @class */ (function () {
  74537. function PhysicsViewer(scene) {
  74538. this._impostors = [];
  74539. this._meshes = [];
  74540. this._numMeshes = 0;
  74541. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74542. var physicEngine = this._scene.getPhysicsEngine();
  74543. if (physicEngine) {
  74544. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  74545. }
  74546. }
  74547. PhysicsViewer.prototype._updateDebugMeshes = function () {
  74548. var plugin = this._physicsEnginePlugin;
  74549. for (var i = 0; i < this._numMeshes; i++) {
  74550. var impostor = this._impostors[i];
  74551. if (!impostor) {
  74552. continue;
  74553. }
  74554. if (impostor.isDisposed) {
  74555. this.hideImpostor(this._impostors[i--]);
  74556. }
  74557. else {
  74558. var mesh = this._meshes[i];
  74559. if (mesh && plugin) {
  74560. plugin.syncMeshWithImpostor(mesh, impostor);
  74561. }
  74562. }
  74563. }
  74564. };
  74565. PhysicsViewer.prototype.showImpostor = function (impostor) {
  74566. if (!this._scene) {
  74567. return;
  74568. }
  74569. for (var i = 0; i < this._numMeshes; i++) {
  74570. if (this._impostors[i] == impostor) {
  74571. return;
  74572. }
  74573. }
  74574. var debugMesh = this._getDebugMesh(impostor, this._scene);
  74575. if (debugMesh) {
  74576. this._impostors[this._numMeshes] = impostor;
  74577. this._meshes[this._numMeshes] = debugMesh;
  74578. if (this._numMeshes === 0) {
  74579. this._renderFunction = this._updateDebugMeshes.bind(this);
  74580. this._scene.registerBeforeRender(this._renderFunction);
  74581. }
  74582. this._numMeshes++;
  74583. }
  74584. };
  74585. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  74586. if (!impostor || !this._scene) {
  74587. return;
  74588. }
  74589. var removed = false;
  74590. for (var i = 0; i < this._numMeshes; i++) {
  74591. if (this._impostors[i] == impostor) {
  74592. var mesh = this._meshes[i];
  74593. if (!mesh) {
  74594. continue;
  74595. }
  74596. this._scene.removeMesh(mesh);
  74597. mesh.dispose();
  74598. this._numMeshes--;
  74599. if (this._numMeshes > 0) {
  74600. this._meshes[i] = this._meshes[this._numMeshes];
  74601. this._impostors[i] = this._impostors[this._numMeshes];
  74602. this._meshes[this._numMeshes] = null;
  74603. this._impostors[this._numMeshes] = null;
  74604. }
  74605. else {
  74606. this._meshes[0] = null;
  74607. this._impostors[0] = null;
  74608. }
  74609. removed = true;
  74610. break;
  74611. }
  74612. }
  74613. if (removed && this._numMeshes === 0) {
  74614. this._scene.unregisterBeforeRender(this._renderFunction);
  74615. }
  74616. };
  74617. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  74618. if (!this._debugMaterial) {
  74619. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  74620. this._debugMaterial.wireframe = true;
  74621. }
  74622. return this._debugMaterial;
  74623. };
  74624. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  74625. if (!this._debugBoxMesh) {
  74626. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  74627. this._debugBoxMesh.renderingGroupId = 1;
  74628. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74629. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  74630. scene.removeMesh(this._debugBoxMesh);
  74631. }
  74632. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  74633. };
  74634. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  74635. if (!this._debugSphereMesh) {
  74636. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  74637. this._debugSphereMesh.renderingGroupId = 1;
  74638. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74639. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  74640. scene.removeMesh(this._debugSphereMesh);
  74641. }
  74642. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  74643. };
  74644. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  74645. var mesh = null;
  74646. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  74647. mesh = this._getDebugBoxMesh(scene);
  74648. impostor.getBoxSizeToRef(mesh.scaling);
  74649. }
  74650. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  74651. mesh = this._getDebugSphereMesh(scene);
  74652. var radius = impostor.getRadius();
  74653. mesh.scaling.x = radius * 2;
  74654. mesh.scaling.y = radius * 2;
  74655. mesh.scaling.z = radius * 2;
  74656. }
  74657. return mesh;
  74658. };
  74659. PhysicsViewer.prototype.dispose = function () {
  74660. for (var i = 0; i < this._numMeshes; i++) {
  74661. this.hideImpostor(this._impostors[i]);
  74662. }
  74663. if (this._debugBoxMesh) {
  74664. this._debugBoxMesh.dispose();
  74665. }
  74666. if (this._debugSphereMesh) {
  74667. this._debugSphereMesh.dispose();
  74668. }
  74669. if (this._debugMaterial) {
  74670. this._debugMaterial.dispose();
  74671. }
  74672. this._impostors.length = 0;
  74673. this._scene = null;
  74674. this._physicsEnginePlugin = null;
  74675. };
  74676. return PhysicsViewer;
  74677. }());
  74678. Debug.SkeletonViewer = /** @class */ (function () {
  74679. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  74680. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  74681. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  74682. this.skeleton = skeleton;
  74683. this.mesh = mesh;
  74684. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  74685. this.renderingGroupId = renderingGroupId;
  74686. this.color = BABYLON.Color3.White();
  74687. this._debugLines = new Array();
  74688. this._isEnabled = false;
  74689. this._scene = scene;
  74690. this.update();
  74691. this._renderFunction = this.update.bind(this);
  74692. }
  74693. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  74694. get: function () {
  74695. return this._isEnabled;
  74696. },
  74697. set: function (value) {
  74698. if (this._isEnabled === value) {
  74699. return;
  74700. }
  74701. this._isEnabled = value;
  74702. if (value) {
  74703. this._scene.registerBeforeRender(this._renderFunction);
  74704. }
  74705. else {
  74706. this._scene.unregisterBeforeRender(this._renderFunction);
  74707. }
  74708. },
  74709. enumerable: true,
  74710. configurable: true
  74711. });
  74712. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  74713. if (x === void 0) { x = 0; }
  74714. if (y === void 0) { y = 0; }
  74715. if (z === void 0) { z = 0; }
  74716. var tmat = BABYLON.Tmp.Matrix[0];
  74717. var parentBone = bone.getParent();
  74718. tmat.copyFrom(bone.getLocalMatrix());
  74719. if (x !== 0 || y !== 0 || z !== 0) {
  74720. var tmat2 = BABYLON.Tmp.Matrix[1];
  74721. BABYLON.Matrix.IdentityToRef(tmat2);
  74722. tmat2.m[12] = x;
  74723. tmat2.m[13] = y;
  74724. tmat2.m[14] = z;
  74725. tmat2.multiplyToRef(tmat, tmat);
  74726. }
  74727. if (parentBone) {
  74728. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  74729. }
  74730. tmat.multiplyToRef(meshMat, tmat);
  74731. position.x = tmat.m[12];
  74732. position.y = tmat.m[13];
  74733. position.z = tmat.m[14];
  74734. };
  74735. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  74736. var len = bones.length;
  74737. var meshPos = this.mesh.position;
  74738. for (var i = 0; i < len; i++) {
  74739. var bone = bones[i];
  74740. var points = this._debugLines[i];
  74741. if (!points) {
  74742. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74743. this._debugLines[i] = points;
  74744. }
  74745. this._getBonePosition(points[0], bone, meshMat);
  74746. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  74747. points[0].subtractInPlace(meshPos);
  74748. points[1].subtractInPlace(meshPos);
  74749. }
  74750. };
  74751. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  74752. var len = bones.length;
  74753. var boneNum = 0;
  74754. var meshPos = this.mesh.position;
  74755. for (var i = len - 1; i >= 0; i--) {
  74756. var childBone = bones[i];
  74757. var parentBone = childBone.getParent();
  74758. if (!parentBone) {
  74759. continue;
  74760. }
  74761. var points = this._debugLines[boneNum];
  74762. if (!points) {
  74763. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74764. this._debugLines[boneNum] = points;
  74765. }
  74766. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  74767. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  74768. points[0].subtractInPlace(meshPos);
  74769. points[1].subtractInPlace(meshPos);
  74770. boneNum++;
  74771. }
  74772. };
  74773. SkeletonViewer.prototype.update = function () {
  74774. if (this.autoUpdateBonesMatrices) {
  74775. this.skeleton.computeAbsoluteTransforms();
  74776. }
  74777. if (this.skeleton.bones[0].length === undefined) {
  74778. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74779. }
  74780. else {
  74781. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74782. }
  74783. if (!this._debugMesh) {
  74784. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  74785. this._debugMesh.renderingGroupId = this.renderingGroupId;
  74786. }
  74787. else {
  74788. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  74789. }
  74790. this._debugMesh.position.copyFrom(this.mesh.position);
  74791. this._debugMesh.color = this.color;
  74792. };
  74793. SkeletonViewer.prototype.dispose = function () {
  74794. if (this._debugMesh) {
  74795. this.isEnabled = false;
  74796. this._debugMesh.dispose();
  74797. this._debugMesh = null;
  74798. }
  74799. };
  74800. return SkeletonViewer;
  74801. }());
  74802. return Debug;
  74803. }());
  74804. BABYLON.Debug = Debug;
  74805. })(BABYLON || (BABYLON = {}));
  74806. //# sourceMappingURL=babylon.debugModules.js.map
  74807. var BABYLON;
  74808. (function (BABYLON) {
  74809. var RayHelper = /** @class */ (function () {
  74810. function RayHelper(ray) {
  74811. this.ray = ray;
  74812. }
  74813. RayHelper.CreateAndShow = function (ray, scene, color) {
  74814. var helper = new RayHelper(ray);
  74815. helper.show(scene, color);
  74816. return helper;
  74817. };
  74818. RayHelper.prototype.show = function (scene, color) {
  74819. if (!this._renderFunction && this.ray) {
  74820. var ray = this.ray;
  74821. this._renderFunction = this._render.bind(this);
  74822. this._scene = scene;
  74823. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  74824. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  74825. if (this._renderFunction) {
  74826. this._scene.registerBeforeRender(this._renderFunction);
  74827. }
  74828. }
  74829. if (color && this._renderLine) {
  74830. this._renderLine.color.copyFrom(color);
  74831. }
  74832. };
  74833. RayHelper.prototype.hide = function () {
  74834. if (this._renderFunction && this._scene) {
  74835. this._scene.unregisterBeforeRender(this._renderFunction);
  74836. this._scene = null;
  74837. this._renderFunction = null;
  74838. if (this._renderLine) {
  74839. this._renderLine.dispose();
  74840. this._renderLine = null;
  74841. }
  74842. this._renderPoints = [];
  74843. }
  74844. };
  74845. RayHelper.prototype._render = function () {
  74846. var ray = this.ray;
  74847. if (!ray) {
  74848. return;
  74849. }
  74850. var point = this._renderPoints[1];
  74851. var len = Math.min(ray.length, 1000000);
  74852. point.copyFrom(ray.direction);
  74853. point.scaleInPlace(len);
  74854. point.addInPlace(ray.origin);
  74855. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  74856. };
  74857. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  74858. this._attachedToMesh = mesh;
  74859. var ray = this.ray;
  74860. if (!ray) {
  74861. return;
  74862. }
  74863. if (!ray.direction) {
  74864. ray.direction = BABYLON.Vector3.Zero();
  74865. }
  74866. if (!ray.origin) {
  74867. ray.origin = BABYLON.Vector3.Zero();
  74868. }
  74869. if (length) {
  74870. ray.length = length;
  74871. }
  74872. if (!meshSpaceOrigin) {
  74873. meshSpaceOrigin = BABYLON.Vector3.Zero();
  74874. }
  74875. if (!meshSpaceDirection) {
  74876. // -1 so that this will work with Mesh.lookAt
  74877. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  74878. }
  74879. if (!this._meshSpaceDirection) {
  74880. this._meshSpaceDirection = meshSpaceDirection.clone();
  74881. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  74882. }
  74883. else {
  74884. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  74885. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  74886. }
  74887. if (!this._updateToMeshFunction) {
  74888. this._updateToMeshFunction = this._updateToMesh.bind(this);
  74889. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  74890. }
  74891. this._updateToMesh();
  74892. };
  74893. RayHelper.prototype.detachFromMesh = function () {
  74894. if (this._attachedToMesh) {
  74895. if (this._updateToMeshFunction) {
  74896. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  74897. }
  74898. this._attachedToMesh = null;
  74899. this._updateToMeshFunction = null;
  74900. }
  74901. };
  74902. RayHelper.prototype._updateToMesh = function () {
  74903. var ray = this.ray;
  74904. if (!this._attachedToMesh || !ray) {
  74905. return;
  74906. }
  74907. if (this._attachedToMesh._isDisposed) {
  74908. this.detachFromMesh();
  74909. return;
  74910. }
  74911. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  74912. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  74913. };
  74914. RayHelper.prototype.dispose = function () {
  74915. this.hide();
  74916. this.detachFromMesh();
  74917. this.ray = null;
  74918. };
  74919. return RayHelper;
  74920. }());
  74921. BABYLON.RayHelper = RayHelper;
  74922. })(BABYLON || (BABYLON = {}));
  74923. //# sourceMappingURL=babylon.rayHelper.js.map
  74924. var BABYLON;
  74925. (function (BABYLON) {
  74926. // load the inspector using require, if not present in the global namespace.
  74927. var DebugLayer = /** @class */ (function () {
  74928. function DebugLayer(scene) {
  74929. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74930. this._scene = scene;
  74931. // load inspector using require, if it doesn't exist on the global namespace.
  74932. }
  74933. /** Creates the inspector window. */
  74934. DebugLayer.prototype._createInspector = function (config) {
  74935. if (config === void 0) { config = {}; }
  74936. var popup = config.popup || false;
  74937. var initialTab = config.initialTab || 0;
  74938. var parentElement = config.parentElement || null;
  74939. if (!this._inspector) {
  74940. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74941. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  74942. } // else nothing to do,; instance is already existing
  74943. };
  74944. DebugLayer.prototype.isVisible = function () {
  74945. if (!this._inspector) {
  74946. return false;
  74947. }
  74948. return true;
  74949. };
  74950. DebugLayer.prototype.hide = function () {
  74951. if (this._inspector) {
  74952. try {
  74953. this._inspector.dispose();
  74954. }
  74955. catch (e) {
  74956. // If the inspector has been removed directly from the inspector tool
  74957. }
  74958. this._inspector = null;
  74959. }
  74960. };
  74961. DebugLayer.prototype.show = function (config) {
  74962. if (config === void 0) { config = {}; }
  74963. if (typeof this.BJSINSPECTOR == 'undefined') {
  74964. // Load inspector and add it to the DOM
  74965. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  74966. }
  74967. else {
  74968. // Otherwise creates the inspector
  74969. this._createInspector(config);
  74970. }
  74971. };
  74972. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  74973. return DebugLayer;
  74974. }());
  74975. BABYLON.DebugLayer = DebugLayer;
  74976. })(BABYLON || (BABYLON = {}));
  74977. //# sourceMappingURL=babylon.debugLayer.js.map
  74978. var BABYLON;
  74979. (function (BABYLON) {
  74980. var BoundingBoxRenderer = /** @class */ (function () {
  74981. function BoundingBoxRenderer(scene) {
  74982. this.frontColor = new BABYLON.Color3(1, 1, 1);
  74983. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  74984. this.showBackLines = true;
  74985. this.renderList = new BABYLON.SmartArray(32);
  74986. this._vertexBuffers = {};
  74987. this._scene = scene;
  74988. }
  74989. BoundingBoxRenderer.prototype._prepareRessources = function () {
  74990. if (this._colorShader) {
  74991. return;
  74992. }
  74993. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  74994. attributes: [BABYLON.VertexBuffer.PositionKind],
  74995. uniforms: ["world", "viewProjection", "color"]
  74996. });
  74997. var engine = this._scene.getEngine();
  74998. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  74999. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  75000. this._createIndexBuffer();
  75001. };
  75002. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  75003. var engine = this._scene.getEngine();
  75004. 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]);
  75005. };
  75006. BoundingBoxRenderer.prototype._rebuild = function () {
  75007. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75008. if (vb) {
  75009. vb._rebuild();
  75010. }
  75011. this._createIndexBuffer();
  75012. };
  75013. BoundingBoxRenderer.prototype.reset = function () {
  75014. this.renderList.reset();
  75015. };
  75016. BoundingBoxRenderer.prototype.render = function () {
  75017. if (this.renderList.length === 0) {
  75018. return;
  75019. }
  75020. this._prepareRessources();
  75021. if (!this._colorShader.isReady()) {
  75022. return;
  75023. }
  75024. var engine = this._scene.getEngine();
  75025. engine.setDepthWrite(false);
  75026. this._colorShader._preBind();
  75027. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  75028. var boundingBox = this.renderList.data[boundingBoxIndex];
  75029. var min = boundingBox.minimum;
  75030. var max = boundingBox.maximum;
  75031. var diff = max.subtract(min);
  75032. var median = min.add(diff.scale(0.5));
  75033. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  75034. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  75035. .multiply(boundingBox.getWorldMatrix());
  75036. // VBOs
  75037. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  75038. if (this.showBackLines) {
  75039. // Back
  75040. engine.setDepthFunctionToGreaterOrEqual();
  75041. this._scene.resetCachedMaterial();
  75042. this._colorShader.setColor4("color", this.backColor.toColor4());
  75043. this._colorShader.bind(worldMatrix);
  75044. // Draw order
  75045. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75046. }
  75047. // Front
  75048. engine.setDepthFunctionToLess();
  75049. this._scene.resetCachedMaterial();
  75050. this._colorShader.setColor4("color", this.frontColor.toColor4());
  75051. this._colorShader.bind(worldMatrix);
  75052. // Draw order
  75053. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75054. }
  75055. this._colorShader.unbind();
  75056. engine.setDepthFunctionToLessOrEqual();
  75057. engine.setDepthWrite(true);
  75058. };
  75059. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  75060. this._prepareRessources();
  75061. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  75062. return;
  75063. }
  75064. var engine = this._scene.getEngine();
  75065. engine.setDepthWrite(false);
  75066. engine.setColorWrite(false);
  75067. this._colorShader._preBind();
  75068. var boundingBox = mesh._boundingInfo.boundingBox;
  75069. var min = boundingBox.minimum;
  75070. var max = boundingBox.maximum;
  75071. var diff = max.subtract(min);
  75072. var median = min.add(diff.scale(0.5));
  75073. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  75074. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  75075. .multiply(boundingBox.getWorldMatrix());
  75076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  75077. engine.setDepthFunctionToLess();
  75078. this._scene.resetCachedMaterial();
  75079. this._colorShader.bind(worldMatrix);
  75080. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75081. this._colorShader.unbind();
  75082. engine.setDepthFunctionToLessOrEqual();
  75083. engine.setDepthWrite(true);
  75084. engine.setColorWrite(true);
  75085. };
  75086. BoundingBoxRenderer.prototype.dispose = function () {
  75087. if (!this._colorShader) {
  75088. return;
  75089. }
  75090. this.renderList.dispose();
  75091. this._colorShader.dispose();
  75092. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75093. if (buffer) {
  75094. buffer.dispose();
  75095. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75096. }
  75097. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75098. };
  75099. return BoundingBoxRenderer;
  75100. }());
  75101. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  75102. })(BABYLON || (BABYLON = {}));
  75103. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  75104. var BABYLON;
  75105. (function (BABYLON) {
  75106. var MorphTarget = /** @class */ (function () {
  75107. function MorphTarget(name, influence) {
  75108. if (influence === void 0) { influence = 0; }
  75109. this.name = name;
  75110. this.animations = new Array();
  75111. this._positions = null;
  75112. this._normals = null;
  75113. this._tangents = null;
  75114. this.onInfluenceChanged = new BABYLON.Observable();
  75115. this.influence = influence;
  75116. }
  75117. Object.defineProperty(MorphTarget.prototype, "influence", {
  75118. get: function () {
  75119. return this._influence;
  75120. },
  75121. set: function (influence) {
  75122. if (this._influence === influence) {
  75123. return;
  75124. }
  75125. var previous = this._influence;
  75126. this._influence = influence;
  75127. if (this.onInfluenceChanged.hasObservers) {
  75128. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  75129. }
  75130. },
  75131. enumerable: true,
  75132. configurable: true
  75133. });
  75134. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  75135. get: function () {
  75136. return !!this._positions;
  75137. },
  75138. enumerable: true,
  75139. configurable: true
  75140. });
  75141. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  75142. get: function () {
  75143. return !!this._normals;
  75144. },
  75145. enumerable: true,
  75146. configurable: true
  75147. });
  75148. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  75149. get: function () {
  75150. return !!this._tangents;
  75151. },
  75152. enumerable: true,
  75153. configurable: true
  75154. });
  75155. MorphTarget.prototype.setPositions = function (data) {
  75156. this._positions = data;
  75157. };
  75158. MorphTarget.prototype.getPositions = function () {
  75159. return this._positions;
  75160. };
  75161. MorphTarget.prototype.setNormals = function (data) {
  75162. this._normals = data;
  75163. };
  75164. MorphTarget.prototype.getNormals = function () {
  75165. return this._normals;
  75166. };
  75167. MorphTarget.prototype.setTangents = function (data) {
  75168. this._tangents = data;
  75169. };
  75170. MorphTarget.prototype.getTangents = function () {
  75171. return this._tangents;
  75172. };
  75173. /**
  75174. * Serializes the current target into a Serialization object.
  75175. * Returns the serialized object.
  75176. */
  75177. MorphTarget.prototype.serialize = function () {
  75178. var serializationObject = {};
  75179. serializationObject.name = this.name;
  75180. serializationObject.influence = this.influence;
  75181. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  75182. if (this.hasNormals) {
  75183. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  75184. }
  75185. if (this.hasTangents) {
  75186. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  75187. }
  75188. // Animations
  75189. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  75190. return serializationObject;
  75191. };
  75192. // Statics
  75193. MorphTarget.Parse = function (serializationObject) {
  75194. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  75195. result.setPositions(serializationObject.positions);
  75196. if (serializationObject.normals) {
  75197. result.setNormals(serializationObject.normals);
  75198. }
  75199. if (serializationObject.tangents) {
  75200. result.setTangents(serializationObject.tangents);
  75201. }
  75202. // Animations
  75203. if (serializationObject.animations) {
  75204. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  75205. var parsedAnimation = serializationObject.animations[animationIndex];
  75206. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  75207. }
  75208. }
  75209. return result;
  75210. };
  75211. MorphTarget.FromMesh = function (mesh, name, influence) {
  75212. if (!name) {
  75213. name = mesh.name;
  75214. }
  75215. var result = new MorphTarget(name, influence);
  75216. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75217. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75218. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  75219. }
  75220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  75221. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  75222. }
  75223. return result;
  75224. };
  75225. return MorphTarget;
  75226. }());
  75227. BABYLON.MorphTarget = MorphTarget;
  75228. })(BABYLON || (BABYLON = {}));
  75229. //# sourceMappingURL=babylon.morphTarget.js.map
  75230. var BABYLON;
  75231. (function (BABYLON) {
  75232. var MorphTargetManager = /** @class */ (function () {
  75233. function MorphTargetManager(scene) {
  75234. if (scene === void 0) { scene = null; }
  75235. this._targets = new Array();
  75236. this._targetObservable = new Array();
  75237. this._activeTargets = new BABYLON.SmartArray(16);
  75238. this._supportsNormals = false;
  75239. this._supportsTangents = false;
  75240. this._vertexCount = 0;
  75241. this._uniqueId = 0;
  75242. this._tempInfluences = new Array();
  75243. if (!scene) {
  75244. scene = BABYLON.Engine.LastCreatedScene;
  75245. }
  75246. this._scene = scene;
  75247. if (this._scene) {
  75248. this._scene.morphTargetManagers.push(this);
  75249. this._uniqueId = this._scene.getUniqueId();
  75250. }
  75251. }
  75252. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  75253. get: function () {
  75254. return this._uniqueId;
  75255. },
  75256. enumerable: true,
  75257. configurable: true
  75258. });
  75259. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  75260. get: function () {
  75261. return this._vertexCount;
  75262. },
  75263. enumerable: true,
  75264. configurable: true
  75265. });
  75266. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  75267. get: function () {
  75268. return this._supportsNormals;
  75269. },
  75270. enumerable: true,
  75271. configurable: true
  75272. });
  75273. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  75274. get: function () {
  75275. return this._supportsTangents;
  75276. },
  75277. enumerable: true,
  75278. configurable: true
  75279. });
  75280. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  75281. get: function () {
  75282. return this._targets.length;
  75283. },
  75284. enumerable: true,
  75285. configurable: true
  75286. });
  75287. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  75288. get: function () {
  75289. return this._activeTargets.length;
  75290. },
  75291. enumerable: true,
  75292. configurable: true
  75293. });
  75294. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  75295. get: function () {
  75296. return this._influences;
  75297. },
  75298. enumerable: true,
  75299. configurable: true
  75300. });
  75301. MorphTargetManager.prototype.getActiveTarget = function (index) {
  75302. return this._activeTargets.data[index];
  75303. };
  75304. MorphTargetManager.prototype.getTarget = function (index) {
  75305. return this._targets[index];
  75306. };
  75307. MorphTargetManager.prototype.addTarget = function (target) {
  75308. var _this = this;
  75309. this._targets.push(target);
  75310. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  75311. _this._syncActiveTargets(needUpdate);
  75312. }));
  75313. this._syncActiveTargets(true);
  75314. };
  75315. MorphTargetManager.prototype.removeTarget = function (target) {
  75316. var index = this._targets.indexOf(target);
  75317. if (index >= 0) {
  75318. this._targets.splice(index, 1);
  75319. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  75320. this._syncActiveTargets(true);
  75321. }
  75322. };
  75323. /**
  75324. * Serializes the current manager into a Serialization object.
  75325. * Returns the serialized object.
  75326. */
  75327. MorphTargetManager.prototype.serialize = function () {
  75328. var serializationObject = {};
  75329. serializationObject.id = this.uniqueId;
  75330. serializationObject.targets = [];
  75331. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75332. var target = _a[_i];
  75333. serializationObject.targets.push(target.serialize());
  75334. }
  75335. return serializationObject;
  75336. };
  75337. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  75338. var influenceCount = 0;
  75339. this._activeTargets.reset();
  75340. this._supportsNormals = true;
  75341. this._supportsTangents = true;
  75342. this._vertexCount = 0;
  75343. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75344. var target = _a[_i];
  75345. this._activeTargets.push(target);
  75346. this._tempInfluences[influenceCount++] = target.influence;
  75347. var positions = target.getPositions();
  75348. if (positions) {
  75349. this._supportsNormals = this._supportsNormals && target.hasNormals;
  75350. this._supportsTangents = this._supportsTangents && target.hasTangents;
  75351. var vertexCount = positions.length / 3;
  75352. if (this._vertexCount === 0) {
  75353. this._vertexCount = vertexCount;
  75354. }
  75355. else if (this._vertexCount !== vertexCount) {
  75356. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  75357. return;
  75358. }
  75359. }
  75360. }
  75361. if (!this._influences || this._influences.length !== influenceCount) {
  75362. this._influences = new Float32Array(influenceCount);
  75363. }
  75364. for (var index = 0; index < influenceCount; index++) {
  75365. this._influences[index] = this._tempInfluences[index];
  75366. }
  75367. if (needUpdate && this._scene) {
  75368. // Flag meshes as dirty to resync with the active targets
  75369. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  75370. var mesh = _c[_b];
  75371. if (mesh.morphTargetManager === this) {
  75372. mesh._syncGeometryWithMorphTargetManager();
  75373. }
  75374. }
  75375. }
  75376. };
  75377. // Statics
  75378. MorphTargetManager.Parse = function (serializationObject, scene) {
  75379. var result = new MorphTargetManager(scene);
  75380. result._uniqueId = serializationObject.id;
  75381. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  75382. var targetData = _a[_i];
  75383. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  75384. }
  75385. return result;
  75386. };
  75387. return MorphTargetManager;
  75388. }());
  75389. BABYLON.MorphTargetManager = MorphTargetManager;
  75390. })(BABYLON || (BABYLON = {}));
  75391. //# sourceMappingURL=babylon.morphTargetManager.js.map
  75392. var BABYLON;
  75393. (function (BABYLON) {
  75394. var Octree = /** @class */ (function () {
  75395. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  75396. if (maxDepth === void 0) { maxDepth = 2; }
  75397. this.maxDepth = maxDepth;
  75398. this.dynamicContent = new Array();
  75399. this._maxBlockCapacity = maxBlockCapacity || 64;
  75400. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  75401. this._creationFunc = creationFunc;
  75402. }
  75403. // Methods
  75404. Octree.prototype.update = function (worldMin, worldMax, entries) {
  75405. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  75406. };
  75407. Octree.prototype.addMesh = function (entry) {
  75408. for (var index = 0; index < this.blocks.length; index++) {
  75409. var block = this.blocks[index];
  75410. block.addEntry(entry);
  75411. }
  75412. };
  75413. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  75414. this._selectionContent.reset();
  75415. for (var index = 0; index < this.blocks.length; index++) {
  75416. var block = this.blocks[index];
  75417. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  75418. }
  75419. if (allowDuplicate) {
  75420. this._selectionContent.concat(this.dynamicContent);
  75421. }
  75422. else {
  75423. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75424. }
  75425. return this._selectionContent;
  75426. };
  75427. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  75428. this._selectionContent.reset();
  75429. for (var index = 0; index < this.blocks.length; index++) {
  75430. var block = this.blocks[index];
  75431. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  75432. }
  75433. if (allowDuplicate) {
  75434. this._selectionContent.concat(this.dynamicContent);
  75435. }
  75436. else {
  75437. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75438. }
  75439. return this._selectionContent;
  75440. };
  75441. Octree.prototype.intersectsRay = function (ray) {
  75442. this._selectionContent.reset();
  75443. for (var index = 0; index < this.blocks.length; index++) {
  75444. var block = this.blocks[index];
  75445. block.intersectsRay(ray, this._selectionContent);
  75446. }
  75447. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75448. return this._selectionContent;
  75449. };
  75450. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  75451. target.blocks = new Array();
  75452. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  75453. // Segmenting space
  75454. for (var x = 0; x < 2; x++) {
  75455. for (var y = 0; y < 2; y++) {
  75456. for (var z = 0; z < 2; z++) {
  75457. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  75458. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  75459. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  75460. block.addEntries(entries);
  75461. target.blocks.push(block);
  75462. }
  75463. }
  75464. }
  75465. };
  75466. Octree.CreationFuncForMeshes = function (entry, block) {
  75467. var boundingInfo = entry.getBoundingInfo();
  75468. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75469. block.entries.push(entry);
  75470. }
  75471. };
  75472. Octree.CreationFuncForSubMeshes = function (entry, block) {
  75473. var boundingInfo = entry.getBoundingInfo();
  75474. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75475. block.entries.push(entry);
  75476. }
  75477. };
  75478. return Octree;
  75479. }());
  75480. BABYLON.Octree = Octree;
  75481. })(BABYLON || (BABYLON = {}));
  75482. //# sourceMappingURL=babylon.octree.js.map
  75483. var BABYLON;
  75484. (function (BABYLON) {
  75485. var OctreeBlock = /** @class */ (function () {
  75486. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  75487. this.entries = new Array();
  75488. this._boundingVectors = new Array();
  75489. this._capacity = capacity;
  75490. this._depth = depth;
  75491. this._maxDepth = maxDepth;
  75492. this._creationFunc = creationFunc;
  75493. this._minPoint = minPoint;
  75494. this._maxPoint = maxPoint;
  75495. this._boundingVectors.push(minPoint.clone());
  75496. this._boundingVectors.push(maxPoint.clone());
  75497. this._boundingVectors.push(minPoint.clone());
  75498. this._boundingVectors[2].x = maxPoint.x;
  75499. this._boundingVectors.push(minPoint.clone());
  75500. this._boundingVectors[3].y = maxPoint.y;
  75501. this._boundingVectors.push(minPoint.clone());
  75502. this._boundingVectors[4].z = maxPoint.z;
  75503. this._boundingVectors.push(maxPoint.clone());
  75504. this._boundingVectors[5].z = minPoint.z;
  75505. this._boundingVectors.push(maxPoint.clone());
  75506. this._boundingVectors[6].x = minPoint.x;
  75507. this._boundingVectors.push(maxPoint.clone());
  75508. this._boundingVectors[7].y = minPoint.y;
  75509. }
  75510. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  75511. // Property
  75512. get: function () {
  75513. return this._capacity;
  75514. },
  75515. enumerable: true,
  75516. configurable: true
  75517. });
  75518. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  75519. get: function () {
  75520. return this._minPoint;
  75521. },
  75522. enumerable: true,
  75523. configurable: true
  75524. });
  75525. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  75526. get: function () {
  75527. return this._maxPoint;
  75528. },
  75529. enumerable: true,
  75530. configurable: true
  75531. });
  75532. // Methods
  75533. OctreeBlock.prototype.addEntry = function (entry) {
  75534. if (this.blocks) {
  75535. for (var index = 0; index < this.blocks.length; index++) {
  75536. var block = this.blocks[index];
  75537. block.addEntry(entry);
  75538. }
  75539. return;
  75540. }
  75541. this._creationFunc(entry, this);
  75542. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  75543. this.createInnerBlocks();
  75544. }
  75545. };
  75546. OctreeBlock.prototype.addEntries = function (entries) {
  75547. for (var index = 0; index < entries.length; index++) {
  75548. var mesh = entries[index];
  75549. this.addEntry(mesh);
  75550. }
  75551. };
  75552. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  75553. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  75554. if (this.blocks) {
  75555. for (var index = 0; index < this.blocks.length; index++) {
  75556. var block = this.blocks[index];
  75557. block.select(frustumPlanes, selection, allowDuplicate);
  75558. }
  75559. return;
  75560. }
  75561. if (allowDuplicate) {
  75562. selection.concat(this.entries);
  75563. }
  75564. else {
  75565. selection.concatWithNoDuplicate(this.entries);
  75566. }
  75567. }
  75568. };
  75569. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  75570. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  75571. if (this.blocks) {
  75572. for (var index = 0; index < this.blocks.length; index++) {
  75573. var block = this.blocks[index];
  75574. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  75575. }
  75576. return;
  75577. }
  75578. if (allowDuplicate) {
  75579. selection.concat(this.entries);
  75580. }
  75581. else {
  75582. selection.concatWithNoDuplicate(this.entries);
  75583. }
  75584. }
  75585. };
  75586. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  75587. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  75588. if (this.blocks) {
  75589. for (var index = 0; index < this.blocks.length; index++) {
  75590. var block = this.blocks[index];
  75591. block.intersectsRay(ray, selection);
  75592. }
  75593. return;
  75594. }
  75595. selection.concatWithNoDuplicate(this.entries);
  75596. }
  75597. };
  75598. OctreeBlock.prototype.createInnerBlocks = function () {
  75599. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  75600. };
  75601. return OctreeBlock;
  75602. }());
  75603. BABYLON.OctreeBlock = OctreeBlock;
  75604. })(BABYLON || (BABYLON = {}));
  75605. //# sourceMappingURL=babylon.octreeBlock.js.map
  75606. var BABYLON;
  75607. (function (BABYLON) {
  75608. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  75609. __extends(VRDistortionCorrectionPostProcess, _super);
  75610. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  75611. var _this = _super.call(this, name, "vrDistortionCorrection", [
  75612. 'LensCenter',
  75613. 'Scale',
  75614. 'ScaleIn',
  75615. 'HmdWarpParam'
  75616. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  75617. _this._isRightEye = isRightEye;
  75618. _this._distortionFactors = vrMetrics.distortionK;
  75619. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  75620. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  75621. _this.adaptScaleToCurrentViewport = true;
  75622. _this.onSizeChangedObservable.add(function () {
  75623. _this.aspectRatio = _this.width * .5 / _this.height;
  75624. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  75625. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  75626. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  75627. });
  75628. _this.onApplyObservable.add(function (effect) {
  75629. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  75630. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  75631. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  75632. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  75633. });
  75634. return _this;
  75635. }
  75636. return VRDistortionCorrectionPostProcess;
  75637. }(BABYLON.PostProcess));
  75638. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  75639. })(BABYLON || (BABYLON = {}));
  75640. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  75641. var BABYLON;
  75642. (function (BABYLON) {
  75643. var AnaglyphPostProcess = /** @class */ (function (_super) {
  75644. __extends(AnaglyphPostProcess, _super);
  75645. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  75646. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  75647. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75648. _this.onApplyObservable.add(function (effect) {
  75649. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  75650. });
  75651. return _this;
  75652. }
  75653. return AnaglyphPostProcess;
  75654. }(BABYLON.PostProcess));
  75655. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  75656. })(BABYLON || (BABYLON = {}));
  75657. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  75658. var BABYLON;
  75659. (function (BABYLON) {
  75660. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  75661. __extends(StereoscopicInterlacePostProcess, _super);
  75662. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  75663. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  75664. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75665. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75666. _this.onSizeChangedObservable.add(function () {
  75667. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75668. });
  75669. _this.onApplyObservable.add(function (effect) {
  75670. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  75671. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  75672. });
  75673. return _this;
  75674. }
  75675. return StereoscopicInterlacePostProcess;
  75676. }(BABYLON.PostProcess));
  75677. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  75678. })(BABYLON || (BABYLON = {}));
  75679. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  75680. var BABYLON;
  75681. (function (BABYLON) {
  75682. /**
  75683. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  75684. * Screen rotation is taken into account.
  75685. */
  75686. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  75687. function FreeCameraDeviceOrientationInput() {
  75688. var _this = this;
  75689. this._screenOrientationAngle = 0;
  75690. this._screenQuaternion = new BABYLON.Quaternion();
  75691. this._alpha = 0;
  75692. this._beta = 0;
  75693. this._gamma = 0;
  75694. this._orientationChanged = function () {
  75695. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  75696. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  75697. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  75698. };
  75699. this._deviceOrientation = function (evt) {
  75700. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  75701. _this._beta = evt.beta !== null ? evt.beta : 0;
  75702. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  75703. };
  75704. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  75705. this._orientationChanged();
  75706. }
  75707. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  75708. get: function () {
  75709. return this._camera;
  75710. },
  75711. set: function (camera) {
  75712. this._camera = camera;
  75713. if (this._camera != null && !this._camera.rotationQuaternion) {
  75714. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  75715. }
  75716. },
  75717. enumerable: true,
  75718. configurable: true
  75719. });
  75720. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75721. window.addEventListener("orientationchange", this._orientationChanged);
  75722. window.addEventListener("deviceorientation", this._deviceOrientation);
  75723. //In certain cases, the attach control is called AFTER orientation was changed,
  75724. //So this is needed.
  75725. this._orientationChanged();
  75726. };
  75727. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  75728. window.removeEventListener("orientationchange", this._orientationChanged);
  75729. window.removeEventListener("deviceorientation", this._deviceOrientation);
  75730. };
  75731. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  75732. //if no device orientation provided, don't update the rotation.
  75733. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  75734. if (!this._alpha)
  75735. return;
  75736. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  75737. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  75738. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  75739. //Mirror on XY Plane
  75740. this._camera.rotationQuaternion.z *= -1;
  75741. this._camera.rotationQuaternion.w *= -1;
  75742. };
  75743. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  75744. return "FreeCameraDeviceOrientationInput";
  75745. };
  75746. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  75747. return "deviceOrientation";
  75748. };
  75749. return FreeCameraDeviceOrientationInput;
  75750. }());
  75751. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  75752. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  75753. })(BABYLON || (BABYLON = {}));
  75754. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  75755. var BABYLON;
  75756. (function (BABYLON) {
  75757. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  75758. function ArcRotateCameraVRDeviceOrientationInput() {
  75759. this.alphaCorrection = 1;
  75760. this.betaCorrection = 1;
  75761. this.gammaCorrection = 1;
  75762. this._alpha = 0;
  75763. this._gamma = 0;
  75764. this._dirty = false;
  75765. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  75766. }
  75767. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75768. this.camera.attachControl(element, noPreventDefault);
  75769. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  75770. };
  75771. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  75772. if (evt.alpha !== null) {
  75773. this._alpha = +evt.alpha | 0;
  75774. }
  75775. if (evt.gamma !== null) {
  75776. this._gamma = +evt.gamma | 0;
  75777. }
  75778. this._dirty = true;
  75779. };
  75780. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  75781. if (this._dirty) {
  75782. this._dirty = false;
  75783. if (this._gamma < 0) {
  75784. this._gamma = 180 + this._gamma;
  75785. }
  75786. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  75787. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  75788. }
  75789. };
  75790. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  75791. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  75792. };
  75793. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  75794. return "ArcRotateCameraVRDeviceOrientationInput";
  75795. };
  75796. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  75797. return "VRDeviceOrientation";
  75798. };
  75799. return ArcRotateCameraVRDeviceOrientationInput;
  75800. }());
  75801. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  75802. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  75803. })(BABYLON || (BABYLON = {}));
  75804. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  75805. var BABYLON;
  75806. (function (BABYLON) {
  75807. var VRCameraMetrics = /** @class */ (function () {
  75808. function VRCameraMetrics() {
  75809. this.compensateDistortion = true;
  75810. }
  75811. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  75812. get: function () {
  75813. return this.hResolution / (2 * this.vResolution);
  75814. },
  75815. enumerable: true,
  75816. configurable: true
  75817. });
  75818. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  75819. get: function () {
  75820. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  75821. },
  75822. enumerable: true,
  75823. configurable: true
  75824. });
  75825. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  75826. get: function () {
  75827. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75828. var h = (4 * meters) / this.hScreenSize;
  75829. return BABYLON.Matrix.Translation(h, 0, 0);
  75830. },
  75831. enumerable: true,
  75832. configurable: true
  75833. });
  75834. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  75835. get: function () {
  75836. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75837. var h = (4 * meters) / this.hScreenSize;
  75838. return BABYLON.Matrix.Translation(-h, 0, 0);
  75839. },
  75840. enumerable: true,
  75841. configurable: true
  75842. });
  75843. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  75844. get: function () {
  75845. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  75846. },
  75847. enumerable: true,
  75848. configurable: true
  75849. });
  75850. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  75851. get: function () {
  75852. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  75853. },
  75854. enumerable: true,
  75855. configurable: true
  75856. });
  75857. VRCameraMetrics.GetDefault = function () {
  75858. var result = new VRCameraMetrics();
  75859. result.hResolution = 1280;
  75860. result.vResolution = 800;
  75861. result.hScreenSize = 0.149759993;
  75862. result.vScreenSize = 0.0935999975;
  75863. result.vScreenCenter = 0.0467999987;
  75864. result.eyeToScreenDistance = 0.0410000011;
  75865. result.lensSeparationDistance = 0.0635000020;
  75866. result.interpupillaryDistance = 0.0640000030;
  75867. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  75868. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  75869. result.postProcessScaleFactor = 1.714605507808412;
  75870. result.lensCenterOffset = 0.151976421;
  75871. return result;
  75872. };
  75873. return VRCameraMetrics;
  75874. }());
  75875. BABYLON.VRCameraMetrics = VRCameraMetrics;
  75876. })(BABYLON || (BABYLON = {}));
  75877. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  75878. var BABYLON;
  75879. (function (BABYLON) {
  75880. /**
  75881. * This represents a WebVR camera.
  75882. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  75883. * @example http://doc.babylonjs.com/how_to/webvr_camera
  75884. */
  75885. var WebVRFreeCamera = /** @class */ (function (_super) {
  75886. __extends(WebVRFreeCamera, _super);
  75887. /**
  75888. * Instantiates a WebVRFreeCamera.
  75889. * @param name The name of the WebVRFreeCamera
  75890. * @param position The starting anchor position for the camera
  75891. * @param scene The scene the camera belongs to
  75892. * @param webVROptions a set of customizable options for the webVRCamera
  75893. */
  75894. function WebVRFreeCamera(name, position, scene, webVROptions) {
  75895. if (webVROptions === void 0) { webVROptions = {}; }
  75896. var _this = _super.call(this, name, position, scene) || this;
  75897. _this.webVROptions = webVROptions;
  75898. /**
  75899. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  75900. */
  75901. _this._vrDevice = null;
  75902. /**
  75903. * The rawPose of the vrDevice.
  75904. */
  75905. _this.rawPose = null;
  75906. _this._specsVersion = "1.1";
  75907. _this._attached = false;
  75908. _this._descendants = [];
  75909. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75910. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75911. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  75912. _this._standingMatrix = null;
  75913. /**
  75914. * Represents device position in babylon space.
  75915. */
  75916. _this.devicePosition = BABYLON.Vector3.Zero();
  75917. /**
  75918. * Represents device rotation in babylon space.
  75919. */
  75920. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  75921. /**
  75922. * The scale of the device to be used when translating from device space to babylon space.
  75923. */
  75924. _this.deviceScaleFactor = 1;
  75925. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75926. _this._worldToDevice = BABYLON.Matrix.Identity();
  75927. /**
  75928. * References to the webVR controllers for the vrDevice.
  75929. */
  75930. _this.controllers = [];
  75931. /**
  75932. * Emits an event when a controller is attached.
  75933. */
  75934. _this.onControllersAttachedObservable = new BABYLON.Observable();
  75935. /**
  75936. * Emits an event when a controller's mesh has been loaded;
  75937. */
  75938. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75939. /**
  75940. * If the rig cameras be used as parent instead of this camera.
  75941. */
  75942. _this.rigParenting = true;
  75943. _this._defaultHeight = undefined;
  75944. _this._workingVector = BABYLON.Vector3.Zero();
  75945. _this._oneVector = BABYLON.Vector3.One();
  75946. _this._workingMatrix = BABYLON.Matrix.Identity();
  75947. _this._cache.position = BABYLON.Vector3.Zero();
  75948. if (webVROptions.defaultHeight) {
  75949. _this._defaultHeight = webVROptions.defaultHeight;
  75950. _this.position.y = _this._defaultHeight;
  75951. }
  75952. _this.minZ = 0.1;
  75953. //legacy support - the compensation boolean was removed.
  75954. if (arguments.length === 5) {
  75955. _this.webVROptions = arguments[4];
  75956. }
  75957. // default webVR options
  75958. if (_this.webVROptions.trackPosition == undefined) {
  75959. _this.webVROptions.trackPosition = true;
  75960. }
  75961. if (_this.webVROptions.controllerMeshes == undefined) {
  75962. _this.webVROptions.controllerMeshes = true;
  75963. }
  75964. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  75965. _this.webVROptions.defaultLightingOnControllers = true;
  75966. }
  75967. _this.rotationQuaternion = new BABYLON.Quaternion();
  75968. if (_this.webVROptions && _this.webVROptions.positionScale) {
  75969. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  75970. }
  75971. //enable VR
  75972. var engine = _this.getEngine();
  75973. _this._onVREnabled = function (success) { if (success) {
  75974. _this.initControllers();
  75975. } };
  75976. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  75977. engine.initWebVR().add(function (event) {
  75978. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  75979. return;
  75980. }
  75981. _this._vrDevice = event.vrDisplay;
  75982. //reset the rig parameters.
  75983. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  75984. if (_this._attached) {
  75985. _this.getEngine().enableVR();
  75986. }
  75987. });
  75988. if (typeof (VRFrameData) !== "undefined")
  75989. _this._frameData = new VRFrameData();
  75990. /**
  75991. * The idea behind the following lines:
  75992. * objects that have the camera as parent should actually have the rig cameras as a parent.
  75993. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  75994. * the second will not show it correctly.
  75995. *
  75996. * To solve this - each object that has the camera as parent will be added to a protected array.
  75997. * When the rig camera renders, it will take this array and set all of those to be its children.
  75998. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  75999. * Amazing!
  76000. */
  76001. scene.onBeforeCameraRenderObservable.add(function (camera) {
  76002. if (camera.parent === _this && _this.rigParenting) {
  76003. _this._descendants = _this.getDescendants(true, function (n) {
  76004. // don't take the cameras or the controllers!
  76005. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  76006. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  76007. return !isController && !isRigCamera;
  76008. });
  76009. _this._descendants.forEach(function (node) {
  76010. node.parent = camera;
  76011. });
  76012. }
  76013. });
  76014. scene.onAfterCameraRenderObservable.add(function (camera) {
  76015. if (camera.parent === _this && _this.rigParenting) {
  76016. _this._descendants.forEach(function (node) {
  76017. node.parent = _this;
  76018. });
  76019. }
  76020. });
  76021. return _this;
  76022. }
  76023. /**
  76024. * Gets the device distance from the ground.
  76025. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  76026. */
  76027. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  76028. if (this._standingMatrix && this._defaultHeight === undefined) {
  76029. // Add standing matrix offset to get real offset from ground in room
  76030. this._standingMatrix.getTranslationToRef(this._workingVector);
  76031. return this._deviceRoomPosition.y + this._workingVector.y;
  76032. }
  76033. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  76034. return this._defaultHeight || 0;
  76035. };
  76036. /**
  76037. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  76038. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  76039. */
  76040. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  76041. var _this = this;
  76042. if (callback === void 0) { callback = function (bool) { }; }
  76043. // Use standing matrix if available
  76044. if (!navigator || !navigator.getVRDisplays) {
  76045. callback(false);
  76046. }
  76047. else {
  76048. navigator.getVRDisplays().then(function (displays) {
  76049. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  76050. callback(false);
  76051. }
  76052. else {
  76053. _this._standingMatrix = new BABYLON.Matrix();
  76054. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  76055. if (!_this.getScene().useRightHandedSystem) {
  76056. [2, 6, 8, 9, 14].forEach(function (num) {
  76057. if (_this._standingMatrix) {
  76058. _this._standingMatrix.m[num] *= -1;
  76059. }
  76060. });
  76061. }
  76062. callback(true);
  76063. }
  76064. });
  76065. }
  76066. };
  76067. /**
  76068. * Disposes the camera
  76069. */
  76070. WebVRFreeCamera.prototype.dispose = function () {
  76071. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  76072. _super.prototype.dispose.call(this);
  76073. };
  76074. /**
  76075. * Gets a vrController by name.
  76076. * @param name The name of the controller to retreive
  76077. * @returns the controller matching the name specified or null if not found
  76078. */
  76079. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  76080. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  76081. var gp = _a[_i];
  76082. if (gp.hand === name) {
  76083. return gp;
  76084. }
  76085. }
  76086. return null;
  76087. };
  76088. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  76089. /**
  76090. * The controller corrisponding to the users left hand.
  76091. */
  76092. get: function () {
  76093. if (!this._leftController) {
  76094. this._leftController = this.getControllerByName("left");
  76095. }
  76096. return this._leftController;
  76097. },
  76098. enumerable: true,
  76099. configurable: true
  76100. });
  76101. ;
  76102. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  76103. /**
  76104. * The controller corrisponding to the users right hand.
  76105. */
  76106. get: function () {
  76107. if (!this._rightController) {
  76108. this._rightController = this.getControllerByName("right");
  76109. }
  76110. return this._rightController;
  76111. },
  76112. enumerable: true,
  76113. configurable: true
  76114. });
  76115. ;
  76116. /**
  76117. * Casts a ray forward from the vrCamera's gaze.
  76118. * @param length Length of the ray (default: 100)
  76119. * @returns the ray corrisponding to the gaze
  76120. */
  76121. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  76122. if (length === void 0) { length = 100; }
  76123. if (this.leftCamera) {
  76124. // Use left eye to avoid computation to compute center on every call
  76125. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  76126. }
  76127. else {
  76128. return _super.prototype.getForwardRay.call(this, length);
  76129. }
  76130. };
  76131. /**
  76132. * Updates the camera based on device's frame data
  76133. */
  76134. WebVRFreeCamera.prototype._checkInputs = function () {
  76135. if (this._vrDevice && this._vrDevice.isPresenting) {
  76136. this._vrDevice.getFrameData(this._frameData);
  76137. this.updateFromDevice(this._frameData.pose);
  76138. }
  76139. _super.prototype._checkInputs.call(this);
  76140. };
  76141. /**
  76142. * Updates the poseControlled values based on the input device pose.
  76143. * @param poseData Pose coming from the device
  76144. */
  76145. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  76146. if (poseData && poseData.orientation) {
  76147. this.rawPose = poseData;
  76148. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  76149. if (this.getScene().useRightHandedSystem) {
  76150. this._deviceRoomRotationQuaternion.z *= -1;
  76151. this._deviceRoomRotationQuaternion.w *= -1;
  76152. }
  76153. if (this.webVROptions.trackPosition && this.rawPose.position) {
  76154. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  76155. if (this.getScene().useRightHandedSystem) {
  76156. this._deviceRoomPosition.z *= -1;
  76157. }
  76158. }
  76159. }
  76160. };
  76161. /**
  76162. * WebVR's attach control will start broadcasting frames to the device.
  76163. * Note that in certain browsers (chrome for example) this function must be called
  76164. * within a user-interaction callback. Example:
  76165. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  76166. *
  76167. * @param element html element to attach the vrDevice to
  76168. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  76169. */
  76170. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  76171. _super.prototype.attachControl.call(this, element, noPreventDefault);
  76172. this._attached = true;
  76173. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  76174. if (this._vrDevice) {
  76175. this.getEngine().enableVR();
  76176. }
  76177. };
  76178. /**
  76179. * Detaches the camera from the html element and disables VR
  76180. *
  76181. * @param element html element to detach from
  76182. */
  76183. WebVRFreeCamera.prototype.detachControl = function (element) {
  76184. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76185. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76186. _super.prototype.detachControl.call(this, element);
  76187. this._attached = false;
  76188. this.getEngine().disableVR();
  76189. };
  76190. /**
  76191. * @returns the name of this class
  76192. */
  76193. WebVRFreeCamera.prototype.getClassName = function () {
  76194. return "WebVRFreeCamera";
  76195. };
  76196. /**
  76197. * Calls resetPose on the vrDisplay
  76198. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  76199. */
  76200. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  76201. //uses the vrDisplay's "resetPose()".
  76202. //pitch and roll won't be affected.
  76203. this._vrDevice.resetPose();
  76204. };
  76205. /**
  76206. * Updates the rig cameras (left and right eye)
  76207. */
  76208. WebVRFreeCamera.prototype._updateRigCameras = function () {
  76209. var camLeft = this._rigCameras[0];
  76210. var camRight = this._rigCameras[1];
  76211. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76212. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76213. camLeft.position.copyFrom(this._deviceRoomPosition);
  76214. camRight.position.copyFrom(this._deviceRoomPosition);
  76215. };
  76216. /**
  76217. * Updates the cached values of the camera
  76218. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  76219. */
  76220. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  76221. var _this = this;
  76222. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  76223. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  76224. if (!this.updateCacheCalled) {
  76225. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  76226. this.updateCacheCalled = true;
  76227. this.update();
  76228. }
  76229. // Set working vector to the device position in room space rotated by the new rotation
  76230. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  76231. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  76232. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  76233. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  76234. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  76235. // Add translation from anchor position
  76236. this._deviceToWorld.getTranslationToRef(this._workingVector);
  76237. this._workingVector.addInPlace(this.position);
  76238. this._workingVector.subtractInPlace(this._cache.position);
  76239. this._deviceToWorld.setTranslation(this._workingVector);
  76240. // Set an inverted matrix to be used when updating the camera
  76241. this._deviceToWorld.invertToRef(this._worldToDevice);
  76242. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  76243. this.controllers.forEach(function (controller) {
  76244. controller._deviceToWorld = _this._deviceToWorld;
  76245. controller.update();
  76246. });
  76247. }
  76248. if (!ignoreParentClass) {
  76249. _super.prototype._updateCache.call(this);
  76250. }
  76251. this.updateCacheCalled = false;
  76252. };
  76253. /**
  76254. * Updates the current device position and rotation in the babylon world
  76255. */
  76256. WebVRFreeCamera.prototype.update = function () {
  76257. // Get current device position in babylon world
  76258. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  76259. // Get current device rotation in babylon world
  76260. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  76261. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  76262. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  76263. _super.prototype.update.call(this);
  76264. };
  76265. /**
  76266. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  76267. * @returns an identity matrix
  76268. */
  76269. WebVRFreeCamera.prototype._getViewMatrix = function () {
  76270. return BABYLON.Matrix.Identity();
  76271. };
  76272. /**
  76273. * This function is called by the two RIG cameras.
  76274. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  76275. */
  76276. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  76277. var _this = this;
  76278. //WebVR 1.1
  76279. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  76280. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  76281. if (!this.getScene().useRightHandedSystem) {
  76282. [2, 6, 8, 9, 14].forEach(function (num) {
  76283. _this._webvrViewMatrix.m[num] *= -1;
  76284. });
  76285. }
  76286. // update the camera rotation matrix
  76287. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  76288. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  76289. // Computing target and final matrix
  76290. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  76291. var parentCamera = this._cameraRigParams["parentCamera"];
  76292. // should the view matrix be updated with scale and position offset?
  76293. if (parentCamera.deviceScaleFactor !== 1) {
  76294. this._webvrViewMatrix.invert();
  76295. // scale the position, if set
  76296. if (parentCamera.deviceScaleFactor) {
  76297. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  76298. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  76299. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  76300. }
  76301. this._webvrViewMatrix.invert();
  76302. }
  76303. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  76304. return this._webvrViewMatrix;
  76305. };
  76306. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  76307. var _this = this;
  76308. var parentCamera = this.parent;
  76309. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  76310. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  76311. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  76312. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  76313. //babylon compatible matrix
  76314. if (!this.getScene().useRightHandedSystem) {
  76315. [8, 9, 10, 11].forEach(function (num) {
  76316. _this._projectionMatrix.m[num] *= -1;
  76317. });
  76318. }
  76319. return this._projectionMatrix;
  76320. };
  76321. /**
  76322. * Initializes the controllers and their meshes
  76323. */
  76324. WebVRFreeCamera.prototype.initControllers = function () {
  76325. var _this = this;
  76326. this.controllers = [];
  76327. var manager = this.getScene().gamepadManager;
  76328. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76329. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76330. var webVrController = gamepad;
  76331. if (webVrController.defaultModel) {
  76332. webVrController.defaultModel.setEnabled(false);
  76333. }
  76334. if (webVrController.hand === "right") {
  76335. _this._rightController = null;
  76336. }
  76337. if (webVrController.hand === "left") {
  76338. _this._rightController = null;
  76339. }
  76340. var controllerIndex = _this.controllers.indexOf(webVrController);
  76341. if (controllerIndex !== -1) {
  76342. _this.controllers.splice(controllerIndex, 1);
  76343. }
  76344. }
  76345. });
  76346. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76347. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76348. var webVrController_1 = gamepad;
  76349. webVrController_1._deviceToWorld = _this._deviceToWorld;
  76350. if (_this.webVROptions.controllerMeshes) {
  76351. if (webVrController_1.defaultModel) {
  76352. webVrController_1.defaultModel.setEnabled(true);
  76353. }
  76354. else {
  76355. // Load the meshes
  76356. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  76357. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  76358. if (_this.webVROptions.defaultLightingOnControllers) {
  76359. if (!_this._lightOnControllers) {
  76360. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  76361. }
  76362. var activateLightOnSubMeshes_1 = function (mesh, light) {
  76363. var children = mesh.getChildren();
  76364. if (children.length !== 0) {
  76365. children.forEach(function (mesh) {
  76366. light.includedOnlyMeshes.push(mesh);
  76367. activateLightOnSubMeshes_1(mesh, light);
  76368. });
  76369. }
  76370. };
  76371. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  76372. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  76373. }
  76374. });
  76375. }
  76376. }
  76377. webVrController_1.attachToPoseControlledCamera(_this);
  76378. // since this is async - sanity check. Is the controller already stored?
  76379. if (_this.controllers.indexOf(webVrController_1) === -1) {
  76380. //add to the controllers array
  76381. _this.controllers.push(webVrController_1);
  76382. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  76383. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  76384. // So we're overriding setting left & right manually to be sure
  76385. var firstViveWandDetected = false;
  76386. for (var i = 0; i < _this.controllers.length; i++) {
  76387. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76388. if (!firstViveWandDetected) {
  76389. firstViveWandDetected = true;
  76390. _this.controllers[i].hand = "left";
  76391. }
  76392. else {
  76393. _this.controllers[i].hand = "right";
  76394. }
  76395. }
  76396. }
  76397. //did we find enough controllers? Great! let the developer know.
  76398. if (_this.controllers.length >= 2) {
  76399. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  76400. }
  76401. }
  76402. }
  76403. });
  76404. };
  76405. return WebVRFreeCamera;
  76406. }(BABYLON.FreeCamera));
  76407. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  76408. })(BABYLON || (BABYLON = {}));
  76409. //# sourceMappingURL=babylon.webVRCamera.js.map
  76410. var BABYLON;
  76411. (function (BABYLON) {
  76412. // We're mainly based on the logic defined into the FreeCamera code
  76413. /**
  76414. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  76415. * being tilted forward or back and left or right.
  76416. */
  76417. var DeviceOrientationCamera = /** @class */ (function (_super) {
  76418. __extends(DeviceOrientationCamera, _super);
  76419. /**
  76420. * Creates a new device orientation camera. @see DeviceOrientationCamera
  76421. * @param name The name of the camera
  76422. * @param position The start position camera
  76423. * @param scene The scene the camera belongs to
  76424. */
  76425. function DeviceOrientationCamera(name, position, scene) {
  76426. var _this = _super.call(this, name, position, scene) || this;
  76427. _this._quaternionCache = new BABYLON.Quaternion();
  76428. _this.inputs.addDeviceOrientation();
  76429. return _this;
  76430. }
  76431. /**
  76432. * Gets the current instance class name ("DeviceOrientationCamera").
  76433. * This helps avoiding instanceof at run time.
  76434. * @returns the class name
  76435. */
  76436. DeviceOrientationCamera.prototype.getClassName = function () {
  76437. return "DeviceOrientationCamera";
  76438. };
  76439. /**
  76440. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  76441. */
  76442. DeviceOrientationCamera.prototype._checkInputs = function () {
  76443. _super.prototype._checkInputs.call(this);
  76444. this._quaternionCache.copyFrom(this.rotationQuaternion);
  76445. if (this._initialQuaternion) {
  76446. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76447. }
  76448. };
  76449. /**
  76450. * Reset the camera to its default orientation on the specified axis only.
  76451. * @param axis The axis to reset
  76452. */
  76453. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  76454. var _this = this;
  76455. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  76456. //can only work if this camera has a rotation quaternion already.
  76457. if (!this.rotationQuaternion)
  76458. return;
  76459. if (!this._initialQuaternion) {
  76460. this._initialQuaternion = new BABYLON.Quaternion();
  76461. }
  76462. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  76463. ['x', 'y', 'z'].forEach(function (axisName) {
  76464. if (!axis[axisName]) {
  76465. _this._initialQuaternion[axisName] = 0;
  76466. }
  76467. else {
  76468. _this._initialQuaternion[axisName] *= -1;
  76469. }
  76470. });
  76471. this._initialQuaternion.normalize();
  76472. //force rotation update
  76473. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76474. };
  76475. return DeviceOrientationCamera;
  76476. }(BABYLON.FreeCamera));
  76477. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  76478. })(BABYLON || (BABYLON = {}));
  76479. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  76480. var BABYLON;
  76481. (function (BABYLON) {
  76482. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  76483. __extends(VRDeviceOrientationFreeCamera, _super);
  76484. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76485. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76486. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76487. var _this = _super.call(this, name, position, scene) || this;
  76488. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76489. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76490. return _this;
  76491. }
  76492. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  76493. return "VRDeviceOrientationFreeCamera";
  76494. };
  76495. return VRDeviceOrientationFreeCamera;
  76496. }(BABYLON.DeviceOrientationCamera));
  76497. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  76498. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  76499. __extends(VRDeviceOrientationGamepadCamera, _super);
  76500. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76501. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76502. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76503. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  76504. _this.inputs.addGamepad();
  76505. return _this;
  76506. }
  76507. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  76508. return "VRDeviceOrientationGamepadCamera";
  76509. };
  76510. return VRDeviceOrientationGamepadCamera;
  76511. }(VRDeviceOrientationFreeCamera));
  76512. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  76513. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  76514. __extends(VRDeviceOrientationArcRotateCamera, _super);
  76515. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  76516. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76517. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76518. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76519. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76520. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76521. _this.inputs.addVRDeviceOrientation();
  76522. return _this;
  76523. }
  76524. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  76525. return "VRDeviceOrientationArcRotateCamera";
  76526. };
  76527. return VRDeviceOrientationArcRotateCamera;
  76528. }(BABYLON.ArcRotateCamera));
  76529. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  76530. })(BABYLON || (BABYLON = {}));
  76531. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  76532. var BABYLON;
  76533. (function (BABYLON) {
  76534. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  76535. __extends(AnaglyphFreeCamera, _super);
  76536. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  76537. var _this = _super.call(this, name, position, scene) || this;
  76538. _this.interaxialDistance = interaxialDistance;
  76539. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76540. return _this;
  76541. }
  76542. AnaglyphFreeCamera.prototype.getClassName = function () {
  76543. return "AnaglyphFreeCamera";
  76544. };
  76545. return AnaglyphFreeCamera;
  76546. }(BABYLON.FreeCamera));
  76547. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  76548. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  76549. __extends(AnaglyphArcRotateCamera, _super);
  76550. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  76551. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76552. _this.interaxialDistance = interaxialDistance;
  76553. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76554. return _this;
  76555. }
  76556. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  76557. return "AnaglyphArcRotateCamera";
  76558. };
  76559. return AnaglyphArcRotateCamera;
  76560. }(BABYLON.ArcRotateCamera));
  76561. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  76562. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  76563. __extends(AnaglyphGamepadCamera, _super);
  76564. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  76565. var _this = _super.call(this, name, position, scene) || this;
  76566. _this.interaxialDistance = interaxialDistance;
  76567. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76568. return _this;
  76569. }
  76570. AnaglyphGamepadCamera.prototype.getClassName = function () {
  76571. return "AnaglyphGamepadCamera";
  76572. };
  76573. return AnaglyphGamepadCamera;
  76574. }(BABYLON.GamepadCamera));
  76575. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  76576. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  76577. __extends(AnaglyphUniversalCamera, _super);
  76578. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  76579. var _this = _super.call(this, name, position, scene) || this;
  76580. _this.interaxialDistance = interaxialDistance;
  76581. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76582. return _this;
  76583. }
  76584. AnaglyphUniversalCamera.prototype.getClassName = function () {
  76585. return "AnaglyphUniversalCamera";
  76586. };
  76587. return AnaglyphUniversalCamera;
  76588. }(BABYLON.UniversalCamera));
  76589. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  76590. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  76591. __extends(StereoscopicFreeCamera, _super);
  76592. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76593. var _this = _super.call(this, name, position, scene) || this;
  76594. _this.interaxialDistance = interaxialDistance;
  76595. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76596. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76597. return _this;
  76598. }
  76599. StereoscopicFreeCamera.prototype.getClassName = function () {
  76600. return "StereoscopicFreeCamera";
  76601. };
  76602. return StereoscopicFreeCamera;
  76603. }(BABYLON.FreeCamera));
  76604. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  76605. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  76606. __extends(StereoscopicArcRotateCamera, _super);
  76607. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  76608. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76609. _this.interaxialDistance = interaxialDistance;
  76610. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76611. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76612. return _this;
  76613. }
  76614. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  76615. return "StereoscopicArcRotateCamera";
  76616. };
  76617. return StereoscopicArcRotateCamera;
  76618. }(BABYLON.ArcRotateCamera));
  76619. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  76620. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  76621. __extends(StereoscopicGamepadCamera, _super);
  76622. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76623. var _this = _super.call(this, name, position, scene) || this;
  76624. _this.interaxialDistance = interaxialDistance;
  76625. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76626. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76627. return _this;
  76628. }
  76629. StereoscopicGamepadCamera.prototype.getClassName = function () {
  76630. return "StereoscopicGamepadCamera";
  76631. };
  76632. return StereoscopicGamepadCamera;
  76633. }(BABYLON.GamepadCamera));
  76634. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  76635. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  76636. __extends(StereoscopicUniversalCamera, _super);
  76637. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76638. var _this = _super.call(this, name, position, scene) || this;
  76639. _this.interaxialDistance = interaxialDistance;
  76640. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76641. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76642. return _this;
  76643. }
  76644. StereoscopicUniversalCamera.prototype.getClassName = function () {
  76645. return "StereoscopicUniversalCamera";
  76646. };
  76647. return StereoscopicUniversalCamera;
  76648. }(BABYLON.UniversalCamera));
  76649. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  76650. })(BABYLON || (BABYLON = {}));
  76651. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  76652. var BABYLON;
  76653. (function (BABYLON) {
  76654. /**
  76655. * Helps to quickly add VR support to an existing scene.
  76656. * See http://doc.babylonjs.com/how_to/webvr_helper
  76657. */
  76658. var VRExperienceHelper = /** @class */ (function () {
  76659. /**
  76660. * Instantiates a VRExperienceHelper.
  76661. * Helps to quickly add VR support to an existing scene.
  76662. * @param scene The scene the VRExperienceHelper belongs to.
  76663. * @param webVROptions Options to modify the vr experience helper's behavior.
  76664. */
  76665. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  76666. if (webVROptions === void 0) { webVROptions = {}; }
  76667. var _this = this;
  76668. this.webVROptions = webVROptions;
  76669. // Can the system support WebVR, even if a headset isn't plugged in?
  76670. this._webVRsupported = false;
  76671. // If WebVR is supported, is a headset plugged in and are we ready to present?
  76672. this._webVRready = false;
  76673. // Are we waiting for the requestPresent callback to complete?
  76674. this._webVRrequesting = false;
  76675. // Are we presenting to the headset right now?
  76676. this._webVRpresenting = false;
  76677. // Are we presenting in the fullscreen fallback?
  76678. this._fullscreenVRpresenting = false;
  76679. /**
  76680. * Observable raised when entering VR.
  76681. */
  76682. this.onEnteringVRObservable = new BABYLON.Observable();
  76683. /**
  76684. * Observable raised when exiting VR.
  76685. */
  76686. this.onExitingVRObservable = new BABYLON.Observable();
  76687. /**
  76688. * Observable raised when controller mesh is loaded.
  76689. */
  76690. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76691. this._useCustomVRButton = false;
  76692. this._teleportationRequested = false;
  76693. this._teleportationEnabledOnLeftController = false;
  76694. this._teleportationEnabledOnRightController = false;
  76695. this._interactionsEnabledOnLeftController = false;
  76696. this._interactionsEnabledOnRightController = false;
  76697. this._leftControllerReady = false;
  76698. this._rightControllerReady = false;
  76699. this._floorMeshesCollection = [];
  76700. this._teleportationAllowed = false;
  76701. this._rotationAllowed = true;
  76702. this._teleportationRequestInitiated = false;
  76703. this._teleportationBackRequestInitiated = false;
  76704. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  76705. this._rotationRightAsked = false;
  76706. this._rotationLeftAsked = false;
  76707. this._isDefaultTeleportationTarget = true;
  76708. this._teleportationFillColor = "#444444";
  76709. this._teleportationBorderColor = "#FFFFFF";
  76710. this._rotationAngle = 0;
  76711. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  76712. this._padSensibilityUp = 0.65;
  76713. this._padSensibilityDown = 0.35;
  76714. /**
  76715. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  76716. */
  76717. this.onNewMeshSelected = new BABYLON.Observable();
  76718. /**
  76719. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  76720. */
  76721. this.onNewMeshPicked = new BABYLON.Observable();
  76722. /**
  76723. * Observable raised before camera teleportation
  76724. */
  76725. this.onBeforeCameraTeleport = new BABYLON.Observable();
  76726. /**
  76727. * Observable raised after camera teleportation
  76728. */
  76729. this.onAfterCameraTeleport = new BABYLON.Observable();
  76730. /**
  76731. * Observable raised when current selected mesh gets unselected
  76732. */
  76733. this.onSelectedMeshUnselected = new BABYLON.Observable();
  76734. /**
  76735. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  76736. */
  76737. this.teleportationEnabled = true;
  76738. this._pointerDownOnMeshAsked = false;
  76739. this._isActionableMesh = false;
  76740. this._teleportationInitialized = false;
  76741. this._interactionsEnabled = false;
  76742. this._interactionsRequested = false;
  76743. this._displayGaze = true;
  76744. this._displayLaserPointer = true;
  76745. this._dpadPressed = true;
  76746. this._onResize = function () {
  76747. _this.moveButtonToBottomRight();
  76748. if (_this._fullscreenVRpresenting && _this._webVRready) {
  76749. _this.exitVR();
  76750. }
  76751. };
  76752. this._onFullscreenChange = function () {
  76753. if (document.fullscreen !== undefined) {
  76754. _this._fullscreenVRpresenting = document.fullscreen;
  76755. }
  76756. else if (document.mozFullScreen !== undefined) {
  76757. _this._fullscreenVRpresenting = document.mozFullScreen;
  76758. }
  76759. else if (document.webkitIsFullScreen !== undefined) {
  76760. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  76761. }
  76762. else if (document.msIsFullScreen !== undefined) {
  76763. _this._fullscreenVRpresenting = document.msIsFullScreen;
  76764. }
  76765. if (!_this._fullscreenVRpresenting && _this._canvas) {
  76766. _this.exitVR();
  76767. if (!_this._useCustomVRButton) {
  76768. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  76769. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  76770. }
  76771. }
  76772. };
  76773. this.beforeRender = function () {
  76774. _this._castRayAndSelectObject();
  76775. };
  76776. this._onNewGamepadConnected = function (gamepad) {
  76777. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76778. if (gamepad.leftStick) {
  76779. gamepad.onleftstickchanged(function (stickValues) {
  76780. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  76781. // Listening to classic/xbox gamepad only if no VR controller is active
  76782. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  76783. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  76784. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  76785. _this._checkTeleportWithRay(stickValues);
  76786. _this._checkTeleportBackwards(stickValues);
  76787. }
  76788. }
  76789. });
  76790. }
  76791. if (gamepad.rightStick) {
  76792. gamepad.onrightstickchanged(function (stickValues) {
  76793. if (_this._teleportationInitialized) {
  76794. _this._checkRotate(stickValues);
  76795. }
  76796. });
  76797. }
  76798. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  76799. gamepad.onbuttondown(function (buttonPressed) {
  76800. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76801. _this._selectionPointerDown();
  76802. }
  76803. });
  76804. gamepad.onbuttonup(function (buttonPressed) {
  76805. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76806. _this._selectionPointerUp();
  76807. }
  76808. });
  76809. }
  76810. }
  76811. else {
  76812. var webVRController = gamepad;
  76813. _this._tryEnableInteractionOnController(webVRController);
  76814. }
  76815. };
  76816. // 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
  76817. this._tryEnableInteractionOnController = function (webVRController) {
  76818. if (webVRController.hand === "left") {
  76819. _this._leftControllerReady = true;
  76820. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  76821. _this._enableInteractionOnController(webVRController);
  76822. }
  76823. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  76824. _this._enableTeleportationOnController(webVRController);
  76825. }
  76826. }
  76827. if (webVRController.hand === "right") {
  76828. _this._rightControllerReady = true;
  76829. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  76830. _this._enableInteractionOnController(webVRController);
  76831. }
  76832. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  76833. _this._enableTeleportationOnController(webVRController);
  76834. }
  76835. }
  76836. };
  76837. this._onNewGamepadDisconnected = function (gamepad) {
  76838. if (gamepad instanceof BABYLON.WebVRController) {
  76839. if (gamepad.hand === "left") {
  76840. _this._interactionsEnabledOnLeftController = false;
  76841. _this._teleportationEnabledOnLeftController = false;
  76842. _this._leftControllerReady = false;
  76843. if (_this._leftLaserPointer) {
  76844. _this._leftLaserPointer.dispose();
  76845. }
  76846. }
  76847. if (gamepad.hand === "right") {
  76848. _this._interactionsEnabledOnRightController = false;
  76849. _this._teleportationEnabledOnRightController = false;
  76850. _this._rightControllerReady = false;
  76851. if (_this._rightLaserPointer) {
  76852. _this._rightLaserPointer.dispose();
  76853. }
  76854. }
  76855. }
  76856. };
  76857. this._workingVector = BABYLON.Vector3.Zero();
  76858. this._workingQuaternion = BABYLON.Quaternion.Identity();
  76859. this._workingMatrix = BABYLON.Matrix.Identity();
  76860. this._scene = scene;
  76861. this._canvas = scene.getEngine().getRenderingCanvas();
  76862. // Parse options
  76863. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  76864. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  76865. }
  76866. if (webVROptions.createDeviceOrientationCamera === undefined) {
  76867. webVROptions.createDeviceOrientationCamera = true;
  76868. }
  76869. if (webVROptions.defaultHeight === undefined) {
  76870. webVROptions.defaultHeight = 1.7;
  76871. }
  76872. if (webVROptions.useCustomVRButton) {
  76873. this._useCustomVRButton = true;
  76874. if (webVROptions.customVRButton) {
  76875. this._btnVR = webVROptions.customVRButton;
  76876. }
  76877. }
  76878. if (webVROptions.rayLength) {
  76879. this._rayLength = webVROptions.rayLength;
  76880. }
  76881. this._defaultHeight = webVROptions.defaultHeight;
  76882. // Set position
  76883. if (this._scene.activeCamera) {
  76884. this._position = this._scene.activeCamera.position.clone();
  76885. }
  76886. else {
  76887. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  76888. }
  76889. // Set non-vr camera
  76890. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  76891. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  76892. // Copy data from existing camera
  76893. if (this._scene.activeCamera) {
  76894. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  76895. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  76896. // Set rotation from previous camera
  76897. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  76898. var targetCamera = this._scene.activeCamera;
  76899. if (targetCamera.rotationQuaternion) {
  76900. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  76901. }
  76902. else {
  76903. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  76904. }
  76905. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  76906. }
  76907. }
  76908. this._scene.activeCamera = this._deviceOrientationCamera;
  76909. if (this._canvas) {
  76910. this._scene.activeCamera.attachControl(this._canvas);
  76911. }
  76912. }
  76913. else {
  76914. this._existingCamera = this._scene.activeCamera;
  76915. }
  76916. // Create VR cameras
  76917. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76918. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  76919. }
  76920. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  76921. this._webVRCamera.useStandingMatrix();
  76922. // Create default button
  76923. if (!this._useCustomVRButton) {
  76924. this._btnVR = document.createElement("BUTTON");
  76925. this._btnVR.className = "babylonVRicon";
  76926. this._btnVR.id = "babylonVRiconbtn";
  76927. this._btnVR.title = "Click to switch to VR";
  76928. 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) }";
  76929. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  76930. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  76931. // css += ".babylonVRicon.vrdisplaysupported { }";
  76932. // css += ".babylonVRicon.vrdisplayready { }";
  76933. // css += ".babylonVRicon.vrdisplayrequesting { }";
  76934. var style = document.createElement('style');
  76935. style.appendChild(document.createTextNode(css));
  76936. document.getElementsByTagName('head')[0].appendChild(style);
  76937. this.moveButtonToBottomRight();
  76938. }
  76939. // VR button click event
  76940. if (this._btnVR) {
  76941. this._btnVR.addEventListener("click", function () {
  76942. if (!_this.isInVRMode) {
  76943. _this.enterVR();
  76944. }
  76945. else {
  76946. _this.exitVR();
  76947. }
  76948. });
  76949. }
  76950. // Window events
  76951. window.addEventListener("resize", this._onResize);
  76952. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  76953. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  76954. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  76955. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  76956. // Display vr button when headset is connected
  76957. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76958. this.displayVRButton();
  76959. }
  76960. else {
  76961. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  76962. if (e.vrDisplay) {
  76963. _this.displayVRButton();
  76964. }
  76965. });
  76966. }
  76967. // Exiting VR mode using 'ESC' key on desktop
  76968. this._onKeyDown = function (event) {
  76969. if (event.keyCode === 27 && _this.isInVRMode) {
  76970. _this.exitVR();
  76971. }
  76972. };
  76973. document.addEventListener("keydown", this._onKeyDown);
  76974. // Exiting VR mode double tapping the touch screen
  76975. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  76976. if (_this.isInVRMode) {
  76977. _this.exitVR();
  76978. if (_this._fullscreenVRpresenting) {
  76979. _this._scene.getEngine().switchFullscreen(true);
  76980. }
  76981. }
  76982. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  76983. // Listen for WebVR display changes
  76984. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  76985. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  76986. this._onVRRequestPresentStart = function () {
  76987. _this._webVRrequesting = true;
  76988. _this.updateButtonVisibility();
  76989. };
  76990. this._onVRRequestPresentComplete = function (success) {
  76991. _this._webVRrequesting = false;
  76992. _this.updateButtonVisibility();
  76993. };
  76994. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  76995. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  76996. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  76997. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76998. scene.onDisposeObservable.add(function () {
  76999. _this.dispose();
  77000. });
  77001. // Gamepad connection events
  77002. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  77003. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  77004. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  77005. this.updateButtonVisibility();
  77006. //create easing functions
  77007. this._circleEase = new BABYLON.CircleEase();
  77008. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77009. }
  77010. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  77011. /** Return this.onEnteringVRObservable
  77012. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  77013. */
  77014. get: function () {
  77015. return this.onEnteringVRObservable;
  77016. },
  77017. enumerable: true,
  77018. configurable: true
  77019. });
  77020. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  77021. /** Return this.onExitingVRObservable
  77022. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  77023. */
  77024. get: function () {
  77025. return this.onExitingVRObservable;
  77026. },
  77027. enumerable: true,
  77028. configurable: true
  77029. });
  77030. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  77031. /** Return this.onControllerMeshLoadedObservable
  77032. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  77033. */
  77034. get: function () {
  77035. return this.onControllerMeshLoadedObservable;
  77036. },
  77037. enumerable: true,
  77038. configurable: true
  77039. });
  77040. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  77041. /**
  77042. * The mesh used to display where the user is going to teleport.
  77043. */
  77044. get: function () {
  77045. return this._teleportationTarget;
  77046. },
  77047. /**
  77048. * Sets the mesh to be used to display where the user is going to teleport.
  77049. */
  77050. set: function (value) {
  77051. if (value) {
  77052. value.name = "teleportationTarget";
  77053. this._isDefaultTeleportationTarget = false;
  77054. this._teleportationTarget = value;
  77055. }
  77056. },
  77057. enumerable: true,
  77058. configurable: true
  77059. });
  77060. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  77061. /**
  77062. * If the ray of the gaze should be displayed.
  77063. */
  77064. get: function () {
  77065. return this._displayGaze;
  77066. },
  77067. /**
  77068. * Sets if the ray of the gaze should be displayed.
  77069. */
  77070. set: function (value) {
  77071. this._displayGaze = value;
  77072. if (!value) {
  77073. this._gazeTracker.isVisible = false;
  77074. }
  77075. },
  77076. enumerable: true,
  77077. configurable: true
  77078. });
  77079. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  77080. /**
  77081. * If the ray of the LaserPointer should be displayed.
  77082. */
  77083. get: function () {
  77084. return this._displayLaserPointer;
  77085. },
  77086. /**
  77087. * Sets if the ray of the LaserPointer should be displayed.
  77088. */
  77089. set: function (value) {
  77090. this._displayLaserPointer = value;
  77091. if (!value) {
  77092. if (this._rightLaserPointer) {
  77093. this._rightLaserPointer.isVisible = false;
  77094. }
  77095. if (this._leftLaserPointer) {
  77096. this._leftLaserPointer.isVisible = false;
  77097. }
  77098. }
  77099. else {
  77100. if (this._rightLaserPointer) {
  77101. this._rightLaserPointer.isVisible = true;
  77102. }
  77103. else if (this._leftLaserPointer) {
  77104. this._leftLaserPointer.isVisible = true;
  77105. }
  77106. }
  77107. },
  77108. enumerable: true,
  77109. configurable: true
  77110. });
  77111. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  77112. /**
  77113. * The deviceOrientationCamera used as the camera when not in VR.
  77114. */
  77115. get: function () {
  77116. return this._deviceOrientationCamera;
  77117. },
  77118. enumerable: true,
  77119. configurable: true
  77120. });
  77121. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  77122. /**
  77123. * Based on the current WebVR support, returns the current VR camera used.
  77124. */
  77125. get: function () {
  77126. if (this._webVRready) {
  77127. return this._webVRCamera;
  77128. }
  77129. else {
  77130. return this._scene.activeCamera;
  77131. }
  77132. },
  77133. enumerable: true,
  77134. configurable: true
  77135. });
  77136. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  77137. /**
  77138. * The webVRCamera which is used when in VR.
  77139. */
  77140. get: function () {
  77141. return this._webVRCamera;
  77142. },
  77143. enumerable: true,
  77144. configurable: true
  77145. });
  77146. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  77147. /**
  77148. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  77149. */
  77150. get: function () {
  77151. return this._vrDeviceOrientationCamera;
  77152. },
  77153. enumerable: true,
  77154. configurable: true
  77155. });
  77156. // Raised when one of the controller has loaded successfully its associated default mesh
  77157. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  77158. this._tryEnableInteractionOnController(webVRController);
  77159. try {
  77160. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  77161. }
  77162. catch (err) {
  77163. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  77164. }
  77165. };
  77166. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  77167. /**
  77168. * Gets a value indicating if we are currently in VR mode.
  77169. */
  77170. get: function () {
  77171. return this._webVRpresenting || this._fullscreenVRpresenting;
  77172. },
  77173. enumerable: true,
  77174. configurable: true
  77175. });
  77176. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  77177. var vrDisplay = this._scene.getEngine().getVRDevice();
  77178. if (vrDisplay) {
  77179. var wasPresenting = this._webVRpresenting;
  77180. // A VR display is connected
  77181. this._webVRpresenting = vrDisplay.isPresenting;
  77182. if (wasPresenting && !this._webVRpresenting)
  77183. this.exitVR();
  77184. }
  77185. else {
  77186. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  77187. }
  77188. this.updateButtonVisibility();
  77189. };
  77190. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  77191. this._webVRsupported = eventArgs.vrSupported;
  77192. this._webVRready = !!eventArgs.vrDisplay;
  77193. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  77194. this.updateButtonVisibility();
  77195. };
  77196. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  77197. if (this._canvas && !this._useCustomVRButton) {
  77198. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  77199. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  77200. }
  77201. };
  77202. VRExperienceHelper.prototype.displayVRButton = function () {
  77203. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  77204. document.body.appendChild(this._btnVR);
  77205. this._btnVRDisplayed = true;
  77206. }
  77207. };
  77208. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  77209. if (!this._btnVR || this._useCustomVRButton) {
  77210. return;
  77211. }
  77212. this._btnVR.className = "babylonVRicon";
  77213. if (this.isInVRMode) {
  77214. this._btnVR.className += " vrdisplaypresenting";
  77215. }
  77216. else {
  77217. if (this._webVRready)
  77218. this._btnVR.className += " vrdisplayready";
  77219. if (this._webVRsupported)
  77220. this._btnVR.className += " vrdisplaysupported";
  77221. if (this._webVRrequesting)
  77222. this._btnVR.className += " vrdisplayrequesting";
  77223. }
  77224. };
  77225. /**
  77226. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  77227. * Otherwise, will use the fullscreen API.
  77228. */
  77229. VRExperienceHelper.prototype.enterVR = function () {
  77230. if (this.onEnteringVRObservable) {
  77231. try {
  77232. this.onEnteringVRObservable.notifyObservers(this);
  77233. }
  77234. catch (err) {
  77235. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  77236. }
  77237. }
  77238. if (this._scene.activeCamera) {
  77239. this._position = this._scene.activeCamera.position.clone();
  77240. // make sure that we return to the last active camera
  77241. this._existingCamera = this._scene.activeCamera;
  77242. }
  77243. if (this._webVRrequesting)
  77244. return;
  77245. // If WebVR is supported and a headset is connected
  77246. if (this._webVRready) {
  77247. if (!this._webVRpresenting) {
  77248. this._webVRCamera.position = this._position;
  77249. this._scene.activeCamera = this._webVRCamera;
  77250. }
  77251. }
  77252. else if (this._vrDeviceOrientationCamera) {
  77253. this._vrDeviceOrientationCamera.position = this._position;
  77254. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  77255. this._scene.getEngine().switchFullscreen(true);
  77256. this.updateButtonVisibility();
  77257. }
  77258. if (this._scene.activeCamera && this._canvas) {
  77259. this._scene.activeCamera.attachControl(this._canvas);
  77260. }
  77261. if (this._interactionsEnabled) {
  77262. this._scene.registerBeforeRender(this.beforeRender);
  77263. }
  77264. };
  77265. /**
  77266. * Attempt to exit VR, or fullscreen.
  77267. */
  77268. VRExperienceHelper.prototype.exitVR = function () {
  77269. if (this.onExitingVRObservable) {
  77270. try {
  77271. this.onExitingVRObservable.notifyObservers(this);
  77272. }
  77273. catch (err) {
  77274. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  77275. }
  77276. }
  77277. if (this._webVRpresenting) {
  77278. this._scene.getEngine().disableVR();
  77279. }
  77280. if (this._scene.activeCamera) {
  77281. this._position = this._scene.activeCamera.position.clone();
  77282. }
  77283. if (this._deviceOrientationCamera) {
  77284. this._deviceOrientationCamera.position = this._position;
  77285. this._scene.activeCamera = this._deviceOrientationCamera;
  77286. if (this._canvas) {
  77287. this._scene.activeCamera.attachControl(this._canvas);
  77288. }
  77289. }
  77290. else if (this._existingCamera) {
  77291. this._existingCamera.position = this._position;
  77292. this._scene.activeCamera = this._existingCamera;
  77293. }
  77294. this.updateButtonVisibility();
  77295. if (this._interactionsEnabled) {
  77296. this._scene.unregisterBeforeRender(this.beforeRender);
  77297. }
  77298. };
  77299. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  77300. /**
  77301. * The position of the vr experience helper.
  77302. */
  77303. get: function () {
  77304. return this._position;
  77305. },
  77306. /**
  77307. * Sets the position of the vr experience helper.
  77308. */
  77309. set: function (value) {
  77310. this._position = value;
  77311. if (this._scene.activeCamera) {
  77312. this._scene.activeCamera.position = value;
  77313. }
  77314. },
  77315. enumerable: true,
  77316. configurable: true
  77317. });
  77318. /**
  77319. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  77320. */
  77321. VRExperienceHelper.prototype.enableInteractions = function () {
  77322. var _this = this;
  77323. if (!this._interactionsEnabled) {
  77324. this._interactionsRequested = true;
  77325. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77326. this._enableInteractionOnController(this._webVRCamera.leftController);
  77327. }
  77328. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77329. this._enableInteractionOnController(this._webVRCamera.rightController);
  77330. }
  77331. this._createGazeTracker();
  77332. this.raySelectionPredicate = function (mesh) {
  77333. return mesh.isVisible;
  77334. };
  77335. this.meshSelectionPredicate = function (mesh) {
  77336. return true;
  77337. };
  77338. this._raySelectionPredicate = function (mesh) {
  77339. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  77340. && mesh.name.indexOf("teleportationTarget") === -1
  77341. && mesh.name.indexOf("torusTeleportation") === -1
  77342. && mesh.name.indexOf("laserPointer") === -1)) {
  77343. return _this.raySelectionPredicate(mesh);
  77344. }
  77345. return false;
  77346. };
  77347. this._interactionsEnabled = true;
  77348. }
  77349. };
  77350. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  77351. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  77352. if (this._floorMeshesCollection[i].id === mesh.id) {
  77353. return true;
  77354. }
  77355. }
  77356. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  77357. return true;
  77358. }
  77359. return false;
  77360. };
  77361. /**
  77362. * Adds a floor mesh to be used for teleportation.
  77363. * @param floorMesh the mesh to be used for teleportation.
  77364. */
  77365. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  77366. if (!this._floorMeshesCollection) {
  77367. return;
  77368. }
  77369. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  77370. return;
  77371. }
  77372. this._floorMeshesCollection.push(floorMesh);
  77373. };
  77374. /**
  77375. * Removes a floor mesh from being used for teleportation.
  77376. * @param floorMesh the mesh to be removed.
  77377. */
  77378. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  77379. if (!this._floorMeshesCollection) {
  77380. return;
  77381. }
  77382. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  77383. if (meshIndex !== -1) {
  77384. this._floorMeshesCollection.splice(meshIndex, 1);
  77385. }
  77386. };
  77387. /**
  77388. * Enables interactions and teleportation using the VR controllers and gaze.
  77389. * @param vrTeleportationOptions options to modify teleportation behavior.
  77390. */
  77391. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  77392. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  77393. if (!this._teleportationInitialized) {
  77394. this._teleportationRequested = true;
  77395. this.enableInteractions();
  77396. if (vrTeleportationOptions.floorMeshName) {
  77397. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  77398. }
  77399. if (vrTeleportationOptions.floorMeshes) {
  77400. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  77401. }
  77402. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77403. this._enableTeleportationOnController(this._webVRCamera.leftController);
  77404. }
  77405. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77406. this._enableTeleportationOnController(this._webVRCamera.rightController);
  77407. }
  77408. // Creates an image processing post process for the vignette not relying
  77409. // on the main scene configuration for image processing to reduce setup and spaces
  77410. // (gamma/linear) conflicts.
  77411. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  77412. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77413. imageProcessingConfiguration.vignetteEnabled = true;
  77414. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  77415. this._webVRCamera.detachPostProcess(this._postProcessMove);
  77416. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  77417. this._teleportationInitialized = true;
  77418. if (this._isDefaultTeleportationTarget) {
  77419. this._createTeleportationCircles();
  77420. }
  77421. }
  77422. };
  77423. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  77424. var _this = this;
  77425. var controllerMesh = webVRController.mesh;
  77426. if (controllerMesh) {
  77427. var makeNotPick = function (root) {
  77428. root.name += " laserPointer";
  77429. root.getChildMeshes().forEach(function (c) {
  77430. makeNotPick(c);
  77431. });
  77432. };
  77433. makeNotPick(controllerMesh);
  77434. var childMeshes = controllerMesh.getChildMeshes();
  77435. for (var i = 0; i < childMeshes.length; i++) {
  77436. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  77437. controllerMesh = childMeshes[i];
  77438. break;
  77439. }
  77440. }
  77441. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  77442. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  77443. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77444. laserPointerMaterial.alpha = 0.6;
  77445. laserPointer.material = laserPointerMaterial;
  77446. laserPointer.rotation.x = Math.PI / 2;
  77447. laserPointer.parent = controllerMesh;
  77448. laserPointer.position.z = -0.5;
  77449. laserPointer.isVisible = false;
  77450. if (webVRController.hand === "left") {
  77451. this._leftLaserPointer = laserPointer;
  77452. this._interactionsEnabledOnLeftController = true;
  77453. if (!this._rightLaserPointer) {
  77454. this._leftLaserPointer.isVisible = true;
  77455. }
  77456. }
  77457. else {
  77458. this._rightLaserPointer = laserPointer;
  77459. this._interactionsEnabledOnRightController = true;
  77460. if (!this._leftLaserPointer) {
  77461. this._rightLaserPointer.isVisible = true;
  77462. }
  77463. }
  77464. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  77465. // Enabling / disabling laserPointer
  77466. if (_this._displayLaserPointer && stateObject.value === 1) {
  77467. laserPointer.isVisible = !laserPointer.isVisible;
  77468. // Laser pointer can only be active on left or right, not both at the same time
  77469. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  77470. _this._rightLaserPointer.isVisible = false;
  77471. }
  77472. else if (_this._leftLaserPointer) {
  77473. _this._leftLaserPointer.isVisible = false;
  77474. }
  77475. }
  77476. });
  77477. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  77478. if (!_this._pointerDownOnMeshAsked) {
  77479. if (stateObject.value > _this._padSensibilityUp) {
  77480. _this._selectionPointerDown();
  77481. }
  77482. }
  77483. else if (stateObject.value < _this._padSensibilityDown) {
  77484. _this._selectionPointerUp();
  77485. }
  77486. });
  77487. }
  77488. };
  77489. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  77490. if (webVRController === void 0) { webVRController = null; }
  77491. if (!this._teleportationRequestInitiated) {
  77492. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  77493. if (webVRController) {
  77494. // If laser pointer wasn't enabled yet
  77495. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  77496. this._leftLaserPointer.isVisible = true;
  77497. if (this._rightLaserPointer) {
  77498. this._rightLaserPointer.isVisible = false;
  77499. }
  77500. }
  77501. else if (this._displayLaserPointer && this._rightLaserPointer) {
  77502. this._rightLaserPointer.isVisible = true;
  77503. if (this._leftLaserPointer) {
  77504. this._leftLaserPointer.isVisible = false;
  77505. }
  77506. }
  77507. }
  77508. this._teleportationRequestInitiated = true;
  77509. }
  77510. }
  77511. else {
  77512. // Listening to the proper controller values changes to confirm teleportation
  77513. if (webVRController == null
  77514. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  77515. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  77516. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  77517. if (this._teleportationAllowed) {
  77518. this._teleportationAllowed = false;
  77519. this._teleportCamera();
  77520. }
  77521. this._teleportationRequestInitiated = false;
  77522. }
  77523. }
  77524. }
  77525. };
  77526. VRExperienceHelper.prototype._selectionPointerDown = function () {
  77527. this._pointerDownOnMeshAsked = true;
  77528. if (this._currentMeshSelected && this._currentHit) {
  77529. this._scene.simulatePointerDown(this._currentHit);
  77530. }
  77531. };
  77532. VRExperienceHelper.prototype._selectionPointerUp = function () {
  77533. if (this._currentMeshSelected && this._currentHit) {
  77534. this._scene.simulatePointerUp(this._currentHit);
  77535. }
  77536. this._pointerDownOnMeshAsked = false;
  77537. };
  77538. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  77539. // Only rotate when user is not currently selecting a teleportation location
  77540. if (this._teleportationRequestInitiated) {
  77541. return;
  77542. }
  77543. if (!this._rotationLeftAsked) {
  77544. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  77545. this._rotationLeftAsked = true;
  77546. if (this._rotationAllowed) {
  77547. this._rotateCamera(false);
  77548. }
  77549. }
  77550. }
  77551. else {
  77552. if (stateObject.x > -this._padSensibilityDown) {
  77553. this._rotationLeftAsked = false;
  77554. }
  77555. }
  77556. if (!this._rotationRightAsked) {
  77557. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  77558. this._rotationRightAsked = true;
  77559. if (this._rotationAllowed) {
  77560. this._rotateCamera(true);
  77561. }
  77562. }
  77563. }
  77564. else {
  77565. if (stateObject.x < this._padSensibilityDown) {
  77566. this._rotationRightAsked = false;
  77567. }
  77568. }
  77569. };
  77570. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  77571. // Only teleport backwards when user is not currently selecting a teleportation location
  77572. if (this._teleportationRequestInitiated) {
  77573. return;
  77574. }
  77575. // Teleport backwards
  77576. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  77577. if (!this._teleportationBackRequestInitiated) {
  77578. if (!this.currentVRCamera) {
  77579. return;
  77580. }
  77581. // Get rotation and position of the current camera
  77582. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  77583. var position = this.currentVRCamera.position;
  77584. // If the camera has device position, use that instead
  77585. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  77586. rotation = this.currentVRCamera.deviceRotationQuaternion;
  77587. position = this.currentVRCamera.devicePosition;
  77588. }
  77589. // Get matrix with only the y rotation of the device rotation
  77590. rotation.toEulerAnglesToRef(this._workingVector);
  77591. this._workingVector.z = 0;
  77592. this._workingVector.x = 0;
  77593. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  77594. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  77595. // Rotate backwards ray by device rotation to cast at the ground behind the user
  77596. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  77597. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  77598. var ray = new BABYLON.Ray(position, this._workingVector);
  77599. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77600. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  77601. this._teleportCamera(hit.pickedPoint);
  77602. }
  77603. this._teleportationBackRequestInitiated = true;
  77604. }
  77605. }
  77606. else {
  77607. this._teleportationBackRequestInitiated = false;
  77608. }
  77609. };
  77610. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  77611. var _this = this;
  77612. var controllerMesh = webVRController.mesh;
  77613. if (controllerMesh) {
  77614. if (webVRController.hand === "left") {
  77615. if (!this._interactionsEnabledOnLeftController) {
  77616. this._enableInteractionOnController(webVRController);
  77617. }
  77618. this._teleportationEnabledOnLeftController = true;
  77619. }
  77620. else {
  77621. if (!this._interactionsEnabledOnRightController) {
  77622. this._enableInteractionOnController(webVRController);
  77623. }
  77624. this._teleportationEnabledOnRightController = true;
  77625. }
  77626. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77627. this._dpadPressed = false;
  77628. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  77629. _this._dpadPressed = stateObject.pressed;
  77630. if (!_this._dpadPressed) {
  77631. _this._rotationLeftAsked = false;
  77632. _this._rotationRightAsked = false;
  77633. _this._teleportationBackRequestInitiated = false;
  77634. }
  77635. });
  77636. }
  77637. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  77638. if (_this.teleportationEnabled) {
  77639. _this._checkTeleportBackwards(stateObject);
  77640. _this._checkTeleportWithRay(stateObject, webVRController);
  77641. }
  77642. _this._checkRotate(stateObject);
  77643. });
  77644. }
  77645. };
  77646. // Gaze support used to point to teleport or to interact with an object
  77647. VRExperienceHelper.prototype._createGazeTracker = function () {
  77648. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  77649. this._gazeTracker.bakeCurrentTransformIntoVertices();
  77650. this._gazeTracker.isPickable = false;
  77651. this._gazeTracker.isVisible = false;
  77652. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  77653. targetMat.specularColor = BABYLON.Color3.Black();
  77654. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77655. targetMat.backFaceCulling = false;
  77656. this._gazeTracker.material = targetMat;
  77657. };
  77658. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  77659. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  77660. this._teleportationTarget.isPickable = false;
  77661. var length = 512;
  77662. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  77663. dynamicTexture.hasAlpha = true;
  77664. var context = dynamicTexture.getContext();
  77665. var centerX = length / 2;
  77666. var centerY = length / 2;
  77667. var radius = 200;
  77668. context.beginPath();
  77669. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  77670. context.fillStyle = this._teleportationFillColor;
  77671. context.fill();
  77672. context.lineWidth = 10;
  77673. context.strokeStyle = this._teleportationBorderColor;
  77674. context.stroke();
  77675. context.closePath();
  77676. dynamicTexture.update();
  77677. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  77678. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  77679. this._teleportationTarget.material = teleportationCircleMaterial;
  77680. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  77681. torus.isPickable = false;
  77682. torus.parent = this._teleportationTarget;
  77683. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77684. var keys = [];
  77685. keys.push({
  77686. frame: 0,
  77687. value: 0
  77688. });
  77689. keys.push({
  77690. frame: 30,
  77691. value: 0.4
  77692. });
  77693. keys.push({
  77694. frame: 60,
  77695. value: 0
  77696. });
  77697. animationInnerCircle.setKeys(keys);
  77698. var easingFunction = new BABYLON.SineEase();
  77699. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77700. animationInnerCircle.setEasingFunction(easingFunction);
  77701. torus.animations = [];
  77702. torus.animations.push(animationInnerCircle);
  77703. this._scene.beginAnimation(torus, 0, 60, true);
  77704. this._hideTeleportationTarget();
  77705. };
  77706. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  77707. if (this._teleportationInitialized) {
  77708. this._teleportationTarget.isVisible = true;
  77709. if (this._isDefaultTeleportationTarget) {
  77710. this._teleportationTarget.getChildren()[0].isVisible = true;
  77711. }
  77712. }
  77713. };
  77714. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  77715. if (this._teleportationInitialized) {
  77716. this._teleportationTarget.isVisible = false;
  77717. if (this._isDefaultTeleportationTarget) {
  77718. this._teleportationTarget.getChildren()[0].isVisible = false;
  77719. }
  77720. }
  77721. };
  77722. VRExperienceHelper.prototype._rotateCamera = function (right) {
  77723. var _this = this;
  77724. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77725. return;
  77726. }
  77727. if (right) {
  77728. this._rotationAngle++;
  77729. }
  77730. else {
  77731. this._rotationAngle--;
  77732. }
  77733. this.currentVRCamera.animations = [];
  77734. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  77735. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77736. var animationRotationKeys = [];
  77737. animationRotationKeys.push({
  77738. frame: 0,
  77739. value: this.currentVRCamera.rotationQuaternion
  77740. });
  77741. animationRotationKeys.push({
  77742. frame: 6,
  77743. value: target
  77744. });
  77745. animationRotation.setKeys(animationRotationKeys);
  77746. animationRotation.setEasingFunction(this._circleEase);
  77747. this.currentVRCamera.animations.push(animationRotation);
  77748. this._postProcessMove.animations = [];
  77749. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77750. var vignetteWeightKeys = [];
  77751. vignetteWeightKeys.push({
  77752. frame: 0,
  77753. value: 0
  77754. });
  77755. vignetteWeightKeys.push({
  77756. frame: 3,
  77757. value: 4
  77758. });
  77759. vignetteWeightKeys.push({
  77760. frame: 6,
  77761. value: 0
  77762. });
  77763. animationPP.setKeys(vignetteWeightKeys);
  77764. animationPP.setEasingFunction(this._circleEase);
  77765. this._postProcessMove.animations.push(animationPP);
  77766. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77767. var vignetteStretchKeys = [];
  77768. vignetteStretchKeys.push({
  77769. frame: 0,
  77770. value: 0
  77771. });
  77772. vignetteStretchKeys.push({
  77773. frame: 3,
  77774. value: 10
  77775. });
  77776. vignetteStretchKeys.push({
  77777. frame: 6,
  77778. value: 0
  77779. });
  77780. animationPP2.setKeys(vignetteStretchKeys);
  77781. animationPP2.setEasingFunction(this._circleEase);
  77782. this._postProcessMove.animations.push(animationPP2);
  77783. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77784. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77785. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77786. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  77787. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77788. });
  77789. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  77790. };
  77791. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  77792. if (hit.pickedPoint) {
  77793. this._teleportationAllowed = true;
  77794. if (this._teleportationRequestInitiated) {
  77795. this._displayTeleportationTarget();
  77796. }
  77797. else {
  77798. this._hideTeleportationTarget();
  77799. }
  77800. this._haloCenter.copyFrom(hit.pickedPoint);
  77801. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  77802. var pickNormal = hit.getNormal(true, false);
  77803. if (pickNormal) {
  77804. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77805. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77806. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  77807. }
  77808. this._teleportationTarget.position.y += 0.1;
  77809. }
  77810. };
  77811. VRExperienceHelper.prototype._teleportCamera = function (location) {
  77812. var _this = this;
  77813. if (location === void 0) { location = null; }
  77814. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77815. return;
  77816. }
  77817. if (!location) {
  77818. location = this._haloCenter;
  77819. }
  77820. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  77821. // offset of the headset from the anchor.
  77822. if (this.webVRCamera.leftCamera) {
  77823. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  77824. this._workingVector.subtractInPlace(this.webVRCamera.position);
  77825. location.subtractToRef(this._workingVector, this._workingVector);
  77826. }
  77827. else {
  77828. this._workingVector.copyFrom(location);
  77829. }
  77830. // Add height to account for user's height offset
  77831. if (this.isInVRMode) {
  77832. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  77833. }
  77834. else {
  77835. this._workingVector.y += this._defaultHeight;
  77836. }
  77837. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  77838. // Create animation from the camera's position to the new location
  77839. this.currentVRCamera.animations = [];
  77840. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77841. var animationCameraTeleportationKeys = [{
  77842. frame: 0,
  77843. value: this.currentVRCamera.position
  77844. },
  77845. {
  77846. frame: 11,
  77847. value: this._workingVector
  77848. }
  77849. ];
  77850. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  77851. animationCameraTeleportation.setEasingFunction(this._circleEase);
  77852. this.currentVRCamera.animations.push(animationCameraTeleportation);
  77853. this._postProcessMove.animations = [];
  77854. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77855. var vignetteWeightKeys = [];
  77856. vignetteWeightKeys.push({
  77857. frame: 0,
  77858. value: 0
  77859. });
  77860. vignetteWeightKeys.push({
  77861. frame: 5,
  77862. value: 8
  77863. });
  77864. vignetteWeightKeys.push({
  77865. frame: 11,
  77866. value: 0
  77867. });
  77868. animationPP.setKeys(vignetteWeightKeys);
  77869. this._postProcessMove.animations.push(animationPP);
  77870. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77871. var vignetteStretchKeys = [];
  77872. vignetteStretchKeys.push({
  77873. frame: 0,
  77874. value: 0
  77875. });
  77876. vignetteStretchKeys.push({
  77877. frame: 5,
  77878. value: 10
  77879. });
  77880. vignetteStretchKeys.push({
  77881. frame: 11,
  77882. value: 0
  77883. });
  77884. animationPP2.setKeys(vignetteStretchKeys);
  77885. this._postProcessMove.animations.push(animationPP2);
  77886. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77887. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77888. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77889. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  77890. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77891. });
  77892. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  77893. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  77894. });
  77895. };
  77896. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  77897. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77898. return;
  77899. }
  77900. var ray;
  77901. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  77902. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  77903. }
  77904. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  77905. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  77906. }
  77907. else {
  77908. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  77909. }
  77910. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77911. // Moving the gazeTracker on the mesh face targetted
  77912. if (hit && hit.pickedPoint) {
  77913. if (this._displayGaze) {
  77914. var multiplier = 1;
  77915. this._gazeTracker.isVisible = true;
  77916. if (this._isActionableMesh) {
  77917. multiplier = 3;
  77918. }
  77919. this._gazeTracker.scaling.x = hit.distance * multiplier;
  77920. this._gazeTracker.scaling.y = hit.distance * multiplier;
  77921. this._gazeTracker.scaling.z = hit.distance * multiplier;
  77922. var pickNormal = hit.getNormal();
  77923. // To avoid z-fighting
  77924. var deltaFighting = 0.002;
  77925. if (pickNormal) {
  77926. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77927. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77928. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  77929. }
  77930. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  77931. if (this._gazeTracker.position.x < 0) {
  77932. this._gazeTracker.position.x += deltaFighting;
  77933. }
  77934. else {
  77935. this._gazeTracker.position.x -= deltaFighting;
  77936. }
  77937. if (this._gazeTracker.position.y < 0) {
  77938. this._gazeTracker.position.y += deltaFighting;
  77939. }
  77940. else {
  77941. this._gazeTracker.position.y -= deltaFighting;
  77942. }
  77943. if (this._gazeTracker.position.z < 0) {
  77944. this._gazeTracker.position.z += deltaFighting;
  77945. }
  77946. else {
  77947. this._gazeTracker.position.z -= deltaFighting;
  77948. }
  77949. }
  77950. // Changing the size of the laser pointer based on the distance from the targetted point
  77951. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  77952. this._rightLaserPointer.scaling.y = hit.distance;
  77953. this._rightLaserPointer.position.z = -hit.distance / 2;
  77954. }
  77955. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  77956. this._leftLaserPointer.scaling.y = hit.distance;
  77957. this._leftLaserPointer.position.z = -hit.distance / 2;
  77958. }
  77959. }
  77960. else {
  77961. this._gazeTracker.isVisible = false;
  77962. }
  77963. if (hit && hit.pickedMesh) {
  77964. this._currentHit = hit;
  77965. if (this._pointerDownOnMeshAsked) {
  77966. this._scene.simulatePointerMove(this._currentHit);
  77967. }
  77968. // The object selected is the floor, we're in a teleportation scenario
  77969. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  77970. // Moving the teleportation area to this targetted point
  77971. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  77972. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  77973. this._notifySelectedMeshUnselected();
  77974. }
  77975. this._currentMeshSelected = null;
  77976. this._moveTeleportationSelectorTo(hit);
  77977. return;
  77978. }
  77979. // If not, we're in a selection scenario
  77980. this._hideTeleportationTarget();
  77981. this._teleportationAllowed = false;
  77982. if (hit.pickedMesh !== this._currentMeshSelected) {
  77983. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  77984. this.onNewMeshPicked.notifyObservers(hit);
  77985. this._currentMeshSelected = hit.pickedMesh;
  77986. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  77987. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  77988. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  77989. this._isActionableMesh = true;
  77990. }
  77991. else {
  77992. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77993. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77994. this._isActionableMesh = false;
  77995. }
  77996. try {
  77997. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  77998. }
  77999. catch (err) {
  78000. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  78001. }
  78002. }
  78003. else {
  78004. this._notifySelectedMeshUnselected();
  78005. this._currentMeshSelected = null;
  78006. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78007. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78008. }
  78009. }
  78010. }
  78011. else {
  78012. this._currentHit = null;
  78013. this._notifySelectedMeshUnselected();
  78014. this._currentMeshSelected = null;
  78015. this._teleportationAllowed = false;
  78016. this._hideTeleportationTarget();
  78017. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78018. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78019. }
  78020. };
  78021. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  78022. if (this._currentMeshSelected) {
  78023. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  78024. }
  78025. };
  78026. /**
  78027. * Sets the color of the laser ray from the vr controllers.
  78028. * @param color new color for the ray.
  78029. */
  78030. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  78031. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  78032. this._leftLaserPointer.material.emissiveColor = color;
  78033. }
  78034. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  78035. this._rightLaserPointer.material.emissiveColor = color;
  78036. }
  78037. };
  78038. /**
  78039. * Sets the color of the ray from the vr headsets gaze.
  78040. * @param color new color for the ray.
  78041. */
  78042. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  78043. if (this._gazeTracker.material) {
  78044. this._gazeTracker.material.emissiveColor = color;
  78045. }
  78046. };
  78047. /**
  78048. * Exits VR and disposes of the vr experience helper
  78049. */
  78050. VRExperienceHelper.prototype.dispose = function () {
  78051. if (this.isInVRMode) {
  78052. this.exitVR();
  78053. }
  78054. if (this._passProcessMove) {
  78055. this._passProcessMove.dispose();
  78056. }
  78057. if (this._postProcessMove) {
  78058. this._postProcessMove.dispose();
  78059. }
  78060. if (this._webVRCamera) {
  78061. this._webVRCamera.dispose();
  78062. }
  78063. if (this._vrDeviceOrientationCamera) {
  78064. this._vrDeviceOrientationCamera.dispose();
  78065. }
  78066. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  78067. document.body.removeChild(this._btnVR);
  78068. }
  78069. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  78070. this._deviceOrientationCamera.dispose();
  78071. }
  78072. if (this._gazeTracker) {
  78073. this._gazeTracker.dispose();
  78074. }
  78075. if (this._teleportationTarget) {
  78076. this._teleportationTarget.dispose();
  78077. }
  78078. this._floorMeshesCollection = [];
  78079. document.removeEventListener("keydown", this._onKeyDown);
  78080. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78081. window.removeEventListener("resize", this._onResize);
  78082. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  78083. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  78084. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  78085. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  78086. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  78087. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  78088. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  78089. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78090. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  78091. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  78092. this._scene.unregisterBeforeRender(this.beforeRender);
  78093. };
  78094. /**
  78095. * Gets the name of the VRExperienceHelper class
  78096. * @returns "VRExperienceHelper"
  78097. */
  78098. VRExperienceHelper.prototype.getClassName = function () {
  78099. return "VRExperienceHelper";
  78100. };
  78101. return VRExperienceHelper;
  78102. }());
  78103. BABYLON.VRExperienceHelper = VRExperienceHelper;
  78104. })(BABYLON || (BABYLON = {}));
  78105. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  78106. // Mainly based on these 2 articles :
  78107. // 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
  78108. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  78109. var BABYLON;
  78110. (function (BABYLON) {
  78111. var JoystickAxis;
  78112. (function (JoystickAxis) {
  78113. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  78114. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  78115. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  78116. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  78117. var VirtualJoystick = /** @class */ (function () {
  78118. function VirtualJoystick(leftJoystick) {
  78119. var _this = this;
  78120. if (leftJoystick) {
  78121. this._leftJoystick = true;
  78122. }
  78123. else {
  78124. this._leftJoystick = false;
  78125. }
  78126. VirtualJoystick._globalJoystickIndex++;
  78127. // By default left & right arrow keys are moving the X
  78128. // and up & down keys are moving the Y
  78129. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  78130. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  78131. this.reverseLeftRight = false;
  78132. this.reverseUpDown = false;
  78133. // collections of pointers
  78134. this._touches = new BABYLON.StringDictionary();
  78135. this.deltaPosition = BABYLON.Vector3.Zero();
  78136. this._joystickSensibility = 25;
  78137. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  78138. this._onResize = function (evt) {
  78139. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  78140. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  78141. if (VirtualJoystick.vjCanvas) {
  78142. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  78143. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  78144. }
  78145. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  78146. };
  78147. // injecting a canvas element on top of the canvas 3D game
  78148. if (!VirtualJoystick.vjCanvas) {
  78149. window.addEventListener("resize", this._onResize, false);
  78150. VirtualJoystick.vjCanvas = document.createElement("canvas");
  78151. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  78152. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  78153. VirtualJoystick.vjCanvas.width = window.innerWidth;
  78154. VirtualJoystick.vjCanvas.height = window.innerHeight;
  78155. VirtualJoystick.vjCanvas.style.width = "100%";
  78156. VirtualJoystick.vjCanvas.style.height = "100%";
  78157. VirtualJoystick.vjCanvas.style.position = "absolute";
  78158. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  78159. VirtualJoystick.vjCanvas.style.top = "0px";
  78160. VirtualJoystick.vjCanvas.style.left = "0px";
  78161. VirtualJoystick.vjCanvas.style.zIndex = "5";
  78162. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  78163. // Support for jQuery PEP polyfill
  78164. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  78165. var context = VirtualJoystick.vjCanvas.getContext('2d');
  78166. if (!context) {
  78167. throw new Error("Unable to create canvas for virtual joystick");
  78168. }
  78169. VirtualJoystick.vjCanvasContext = context;
  78170. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  78171. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  78172. document.body.appendChild(VirtualJoystick.vjCanvas);
  78173. }
  78174. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  78175. this.pressed = false;
  78176. // default joystick color
  78177. this._joystickColor = "cyan";
  78178. this._joystickPointerID = -1;
  78179. // current joystick position
  78180. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  78181. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  78182. // origin joystick position
  78183. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  78184. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  78185. this._onPointerDownHandlerRef = function (evt) {
  78186. _this._onPointerDown(evt);
  78187. };
  78188. this._onPointerMoveHandlerRef = function (evt) {
  78189. _this._onPointerMove(evt);
  78190. };
  78191. this._onPointerUpHandlerRef = function (evt) {
  78192. _this._onPointerUp(evt);
  78193. };
  78194. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  78195. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  78196. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  78197. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  78198. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  78199. evt.preventDefault(); // Disables system menu
  78200. }, false);
  78201. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78202. }
  78203. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  78204. this._joystickSensibility = newJoystickSensibility;
  78205. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  78206. };
  78207. VirtualJoystick.prototype._onPointerDown = function (e) {
  78208. var positionOnScreenCondition;
  78209. e.preventDefault();
  78210. if (this._leftJoystick === true) {
  78211. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  78212. }
  78213. else {
  78214. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  78215. }
  78216. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  78217. // First contact will be dedicated to the virtual joystick
  78218. this._joystickPointerID = e.pointerId;
  78219. this._joystickPointerStartPos.x = e.clientX;
  78220. this._joystickPointerStartPos.y = e.clientY;
  78221. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  78222. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  78223. this._deltaJoystickVector.x = 0;
  78224. this._deltaJoystickVector.y = 0;
  78225. this.pressed = true;
  78226. this._touches.add(e.pointerId.toString(), e);
  78227. }
  78228. else {
  78229. // You can only trigger the action buttons with a joystick declared
  78230. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  78231. this._action();
  78232. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  78233. }
  78234. }
  78235. };
  78236. VirtualJoystick.prototype._onPointerMove = function (e) {
  78237. // If the current pointer is the one associated to the joystick (first touch contact)
  78238. if (this._joystickPointerID == e.pointerId) {
  78239. this._joystickPointerPos.x = e.clientX;
  78240. this._joystickPointerPos.y = e.clientY;
  78241. this._deltaJoystickVector = this._joystickPointerPos.clone();
  78242. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  78243. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  78244. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  78245. switch (this._axisTargetedByLeftAndRight) {
  78246. case JoystickAxis.X:
  78247. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  78248. break;
  78249. case JoystickAxis.Y:
  78250. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  78251. break;
  78252. case JoystickAxis.Z:
  78253. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  78254. break;
  78255. }
  78256. var directionUpDown = this.reverseUpDown ? 1 : -1;
  78257. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  78258. switch (this._axisTargetedByUpAndDown) {
  78259. case JoystickAxis.X:
  78260. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  78261. break;
  78262. case JoystickAxis.Y:
  78263. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  78264. break;
  78265. case JoystickAxis.Z:
  78266. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  78267. break;
  78268. }
  78269. }
  78270. else {
  78271. var data = this._touches.get(e.pointerId.toString());
  78272. if (data) {
  78273. data.x = e.clientX;
  78274. data.y = e.clientY;
  78275. }
  78276. }
  78277. };
  78278. VirtualJoystick.prototype._onPointerUp = function (e) {
  78279. if (this._joystickPointerID == e.pointerId) {
  78280. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  78281. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  78282. this._joystickPointerID = -1;
  78283. this.pressed = false;
  78284. }
  78285. else {
  78286. var touch = this._touches.get(e.pointerId.toString());
  78287. if (touch) {
  78288. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78289. }
  78290. }
  78291. this._deltaJoystickVector.x = 0;
  78292. this._deltaJoystickVector.y = 0;
  78293. this._touches.remove(e.pointerId.toString());
  78294. };
  78295. /**
  78296. * Change the color of the virtual joystick
  78297. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  78298. */
  78299. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  78300. this._joystickColor = newColor;
  78301. };
  78302. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  78303. this._action = action;
  78304. };
  78305. // Define which axis you'd like to control for left & right
  78306. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  78307. switch (axis) {
  78308. case JoystickAxis.X:
  78309. case JoystickAxis.Y:
  78310. case JoystickAxis.Z:
  78311. this._axisTargetedByLeftAndRight = axis;
  78312. break;
  78313. default:
  78314. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  78315. break;
  78316. }
  78317. };
  78318. // Define which axis you'd like to control for up & down
  78319. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  78320. switch (axis) {
  78321. case JoystickAxis.X:
  78322. case JoystickAxis.Y:
  78323. case JoystickAxis.Z:
  78324. this._axisTargetedByUpAndDown = axis;
  78325. break;
  78326. default:
  78327. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  78328. break;
  78329. }
  78330. };
  78331. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  78332. var _this = this;
  78333. if (this.pressed) {
  78334. this._touches.forEach(function (key, touch) {
  78335. if (touch.pointerId === _this._joystickPointerID) {
  78336. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  78337. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  78338. VirtualJoystick.vjCanvasContext.beginPath();
  78339. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78340. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78341. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  78342. VirtualJoystick.vjCanvasContext.stroke();
  78343. VirtualJoystick.vjCanvasContext.closePath();
  78344. VirtualJoystick.vjCanvasContext.beginPath();
  78345. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78346. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  78347. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  78348. VirtualJoystick.vjCanvasContext.stroke();
  78349. VirtualJoystick.vjCanvasContext.closePath();
  78350. VirtualJoystick.vjCanvasContext.beginPath();
  78351. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78352. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  78353. VirtualJoystick.vjCanvasContext.stroke();
  78354. VirtualJoystick.vjCanvasContext.closePath();
  78355. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  78356. }
  78357. else {
  78358. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78359. VirtualJoystick.vjCanvasContext.beginPath();
  78360. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  78361. VirtualJoystick.vjCanvasContext.beginPath();
  78362. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  78363. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78364. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  78365. VirtualJoystick.vjCanvasContext.stroke();
  78366. VirtualJoystick.vjCanvasContext.closePath();
  78367. touch.prevX = touch.x;
  78368. touch.prevY = touch.y;
  78369. }
  78370. ;
  78371. });
  78372. }
  78373. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78374. };
  78375. VirtualJoystick.prototype.releaseCanvas = function () {
  78376. if (VirtualJoystick.vjCanvas) {
  78377. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  78378. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  78379. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  78380. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  78381. window.removeEventListener("resize", this._onResize);
  78382. document.body.removeChild(VirtualJoystick.vjCanvas);
  78383. VirtualJoystick.vjCanvas = null;
  78384. }
  78385. };
  78386. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  78387. VirtualJoystick._globalJoystickIndex = 0;
  78388. return VirtualJoystick;
  78389. }());
  78390. BABYLON.VirtualJoystick = VirtualJoystick;
  78391. })(BABYLON || (BABYLON = {}));
  78392. //# sourceMappingURL=babylon.virtualJoystick.js.map
  78393. var BABYLON;
  78394. (function (BABYLON) {
  78395. // We're mainly based on the logic defined into the FreeCamera code
  78396. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  78397. __extends(VirtualJoysticksCamera, _super);
  78398. function VirtualJoysticksCamera(name, position, scene) {
  78399. var _this = _super.call(this, name, position, scene) || this;
  78400. _this.inputs.addVirtualJoystick();
  78401. return _this;
  78402. }
  78403. VirtualJoysticksCamera.prototype.getClassName = function () {
  78404. return "VirtualJoysticksCamera";
  78405. };
  78406. return VirtualJoysticksCamera;
  78407. }(BABYLON.FreeCamera));
  78408. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  78409. })(BABYLON || (BABYLON = {}));
  78410. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  78411. var BABYLON;
  78412. (function (BABYLON) {
  78413. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  78414. function FreeCameraVirtualJoystickInput() {
  78415. }
  78416. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  78417. return this._leftjoystick;
  78418. };
  78419. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  78420. return this._rightjoystick;
  78421. };
  78422. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  78423. if (this._leftjoystick) {
  78424. var camera = this.camera;
  78425. var speed = camera._computeLocalCameraSpeed() * 50;
  78426. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  78427. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  78428. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  78429. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  78430. if (!this._leftjoystick.pressed) {
  78431. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  78432. }
  78433. if (!this._rightjoystick.pressed) {
  78434. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  78435. }
  78436. }
  78437. };
  78438. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  78439. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  78440. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  78441. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  78442. this._leftjoystick.setJoystickSensibility(0.15);
  78443. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  78444. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  78445. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  78446. this._rightjoystick.reverseUpDown = true;
  78447. this._rightjoystick.setJoystickSensibility(0.05);
  78448. this._rightjoystick.setJoystickColor("yellow");
  78449. };
  78450. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  78451. this._leftjoystick.releaseCanvas();
  78452. this._rightjoystick.releaseCanvas();
  78453. };
  78454. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  78455. return "FreeCameraVirtualJoystickInput";
  78456. };
  78457. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  78458. return "virtualJoystick";
  78459. };
  78460. return FreeCameraVirtualJoystickInput;
  78461. }());
  78462. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  78463. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  78464. })(BABYLON || (BABYLON = {}));
  78465. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  78466. var BABYLON;
  78467. (function (BABYLON) {
  78468. var SimplificationSettings = /** @class */ (function () {
  78469. function SimplificationSettings(quality, distance, optimizeMesh) {
  78470. this.quality = quality;
  78471. this.distance = distance;
  78472. this.optimizeMesh = optimizeMesh;
  78473. }
  78474. return SimplificationSettings;
  78475. }());
  78476. BABYLON.SimplificationSettings = SimplificationSettings;
  78477. var SimplificationQueue = /** @class */ (function () {
  78478. function SimplificationQueue() {
  78479. this.running = false;
  78480. this._simplificationArray = [];
  78481. }
  78482. SimplificationQueue.prototype.addTask = function (task) {
  78483. this._simplificationArray.push(task);
  78484. };
  78485. SimplificationQueue.prototype.executeNext = function () {
  78486. var task = this._simplificationArray.pop();
  78487. if (task) {
  78488. this.running = true;
  78489. this.runSimplification(task);
  78490. }
  78491. else {
  78492. this.running = false;
  78493. }
  78494. };
  78495. SimplificationQueue.prototype.runSimplification = function (task) {
  78496. var _this = this;
  78497. if (task.parallelProcessing) {
  78498. //parallel simplifier
  78499. task.settings.forEach(function (setting) {
  78500. var simplifier = _this.getSimplifier(task);
  78501. simplifier.simplify(setting, function (newMesh) {
  78502. task.mesh.addLODLevel(setting.distance, newMesh);
  78503. newMesh.isVisible = true;
  78504. //check if it is the last
  78505. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  78506. //all done, run the success callback.
  78507. task.successCallback();
  78508. }
  78509. _this.executeNext();
  78510. });
  78511. });
  78512. }
  78513. else {
  78514. //single simplifier.
  78515. var simplifier = this.getSimplifier(task);
  78516. var runDecimation = function (setting, callback) {
  78517. simplifier.simplify(setting, function (newMesh) {
  78518. task.mesh.addLODLevel(setting.distance, newMesh);
  78519. newMesh.isVisible = true;
  78520. //run the next quality level
  78521. callback();
  78522. });
  78523. };
  78524. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  78525. runDecimation(task.settings[loop.index], function () {
  78526. loop.executeNext();
  78527. });
  78528. }, function () {
  78529. //execution ended, run the success callback.
  78530. if (task.successCallback) {
  78531. task.successCallback();
  78532. }
  78533. _this.executeNext();
  78534. });
  78535. }
  78536. };
  78537. SimplificationQueue.prototype.getSimplifier = function (task) {
  78538. switch (task.simplificationType) {
  78539. case SimplificationType.QUADRATIC:
  78540. default:
  78541. return new QuadraticErrorSimplification(task.mesh);
  78542. }
  78543. };
  78544. return SimplificationQueue;
  78545. }());
  78546. BABYLON.SimplificationQueue = SimplificationQueue;
  78547. /**
  78548. * The implemented types of simplification.
  78549. * At the moment only Quadratic Error Decimation is implemented.
  78550. */
  78551. var SimplificationType;
  78552. (function (SimplificationType) {
  78553. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  78554. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  78555. var DecimationTriangle = /** @class */ (function () {
  78556. function DecimationTriangle(vertices) {
  78557. this.vertices = vertices;
  78558. this.error = new Array(4);
  78559. this.deleted = false;
  78560. this.isDirty = false;
  78561. this.deletePending = false;
  78562. this.borderFactor = 0;
  78563. }
  78564. return DecimationTriangle;
  78565. }());
  78566. BABYLON.DecimationTriangle = DecimationTriangle;
  78567. var DecimationVertex = /** @class */ (function () {
  78568. function DecimationVertex(position, id) {
  78569. this.position = position;
  78570. this.id = id;
  78571. this.isBorder = true;
  78572. this.q = new QuadraticMatrix();
  78573. this.triangleCount = 0;
  78574. this.triangleStart = 0;
  78575. this.originalOffsets = [];
  78576. }
  78577. DecimationVertex.prototype.updatePosition = function (newPosition) {
  78578. this.position.copyFrom(newPosition);
  78579. };
  78580. return DecimationVertex;
  78581. }());
  78582. BABYLON.DecimationVertex = DecimationVertex;
  78583. var QuadraticMatrix = /** @class */ (function () {
  78584. function QuadraticMatrix(data) {
  78585. this.data = new Array(10);
  78586. for (var i = 0; i < 10; ++i) {
  78587. if (data && data[i]) {
  78588. this.data[i] = data[i];
  78589. }
  78590. else {
  78591. this.data[i] = 0;
  78592. }
  78593. }
  78594. }
  78595. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  78596. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  78597. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  78598. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  78599. return det;
  78600. };
  78601. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  78602. for (var i = 0; i < 10; ++i) {
  78603. this.data[i] += matrix.data[i];
  78604. }
  78605. };
  78606. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  78607. for (var i = 0; i < 10; ++i) {
  78608. this.data[i] += data[i];
  78609. }
  78610. };
  78611. QuadraticMatrix.prototype.add = function (matrix) {
  78612. var m = new QuadraticMatrix();
  78613. for (var i = 0; i < 10; ++i) {
  78614. m.data[i] = this.data[i] + matrix.data[i];
  78615. }
  78616. return m;
  78617. };
  78618. QuadraticMatrix.FromData = function (a, b, c, d) {
  78619. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78620. };
  78621. //returning an array to avoid garbage collection
  78622. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  78623. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  78624. };
  78625. return QuadraticMatrix;
  78626. }());
  78627. BABYLON.QuadraticMatrix = QuadraticMatrix;
  78628. var Reference = /** @class */ (function () {
  78629. function Reference(vertexId, triangleId) {
  78630. this.vertexId = vertexId;
  78631. this.triangleId = triangleId;
  78632. }
  78633. return Reference;
  78634. }());
  78635. BABYLON.Reference = Reference;
  78636. /**
  78637. * An implementation of the Quadratic Error simplification algorithm.
  78638. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  78639. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  78640. * @author RaananW
  78641. */
  78642. var QuadraticErrorSimplification = /** @class */ (function () {
  78643. function QuadraticErrorSimplification(_mesh) {
  78644. this._mesh = _mesh;
  78645. this.syncIterations = 5000;
  78646. this.aggressiveness = 7;
  78647. this.decimationIterations = 100;
  78648. this.boundingBoxEpsilon = BABYLON.Epsilon;
  78649. }
  78650. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  78651. var _this = this;
  78652. this.initDecimatedMesh();
  78653. //iterating through the submeshes array, one after the other.
  78654. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  78655. _this.initWithMesh(loop.index, function () {
  78656. _this.runDecimation(settings, loop.index, function () {
  78657. loop.executeNext();
  78658. });
  78659. }, settings.optimizeMesh);
  78660. }, function () {
  78661. setTimeout(function () {
  78662. successCallback(_this._reconstructedMesh);
  78663. }, 0);
  78664. });
  78665. };
  78666. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  78667. var _this = this;
  78668. var targetCount = ~~(this.triangles.length * settings.quality);
  78669. var deletedTriangles = 0;
  78670. var triangleCount = this.triangles.length;
  78671. var iterationFunction = function (iteration, callback) {
  78672. setTimeout(function () {
  78673. if (iteration % 5 === 0) {
  78674. _this.updateMesh(iteration === 0);
  78675. }
  78676. for (var i = 0; i < _this.triangles.length; ++i) {
  78677. _this.triangles[i].isDirty = false;
  78678. }
  78679. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  78680. var trianglesIterator = function (i) {
  78681. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  78682. var t = _this.triangles[tIdx];
  78683. if (!t)
  78684. return;
  78685. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  78686. return;
  78687. }
  78688. for (var j = 0; j < 3; ++j) {
  78689. if (t.error[j] < threshold) {
  78690. var deleted0 = [];
  78691. var deleted1 = [];
  78692. var v0 = t.vertices[j];
  78693. var v1 = t.vertices[(j + 1) % 3];
  78694. if (v0.isBorder || v1.isBorder)
  78695. continue;
  78696. var p = BABYLON.Vector3.Zero();
  78697. var n = BABYLON.Vector3.Zero();
  78698. var uv = BABYLON.Vector2.Zero();
  78699. var color = new BABYLON.Color4(0, 0, 0, 1);
  78700. _this.calculateError(v0, v1, p, n, uv, color);
  78701. var delTr = new Array();
  78702. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  78703. continue;
  78704. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  78705. continue;
  78706. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  78707. continue;
  78708. var uniqueArray = new Array();
  78709. delTr.forEach(function (deletedT) {
  78710. if (uniqueArray.indexOf(deletedT) === -1) {
  78711. deletedT.deletePending = true;
  78712. uniqueArray.push(deletedT);
  78713. }
  78714. });
  78715. if (uniqueArray.length % 2 !== 0) {
  78716. continue;
  78717. }
  78718. v0.q = v1.q.add(v0.q);
  78719. v0.updatePosition(p);
  78720. var tStart = _this.references.length;
  78721. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  78722. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  78723. var tCount = _this.references.length - tStart;
  78724. if (tCount <= v0.triangleCount) {
  78725. if (tCount) {
  78726. for (var c = 0; c < tCount; c++) {
  78727. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  78728. }
  78729. }
  78730. }
  78731. else {
  78732. v0.triangleStart = tStart;
  78733. }
  78734. v0.triangleCount = tCount;
  78735. break;
  78736. }
  78737. }
  78738. };
  78739. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  78740. }, 0);
  78741. };
  78742. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  78743. if (triangleCount - deletedTriangles <= targetCount)
  78744. loop.breakLoop();
  78745. else {
  78746. iterationFunction(loop.index, function () {
  78747. loop.executeNext();
  78748. });
  78749. }
  78750. }, function () {
  78751. setTimeout(function () {
  78752. //reconstruct this part of the mesh
  78753. _this.reconstructMesh(submeshIndex);
  78754. successCallback();
  78755. }, 0);
  78756. });
  78757. };
  78758. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  78759. var _this = this;
  78760. this.vertices = [];
  78761. this.triangles = [];
  78762. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78763. var indices = this._mesh.getIndices();
  78764. var submesh = this._mesh.subMeshes[submeshIndex];
  78765. var findInVertices = function (positionToSearch) {
  78766. if (optimizeMesh) {
  78767. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  78768. if (_this.vertices[ii].position.equals(positionToSearch)) {
  78769. return _this.vertices[ii];
  78770. }
  78771. }
  78772. }
  78773. return null;
  78774. };
  78775. var vertexReferences = [];
  78776. var vertexInit = function (i) {
  78777. if (!positionData) {
  78778. return;
  78779. }
  78780. var offset = i + submesh.verticesStart;
  78781. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  78782. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  78783. vertex.originalOffsets.push(offset);
  78784. if (vertex.id === _this.vertices.length) {
  78785. _this.vertices.push(vertex);
  78786. }
  78787. vertexReferences.push(vertex.id);
  78788. };
  78789. //var totalVertices = mesh.getTotalVertices();
  78790. var totalVertices = submesh.verticesCount;
  78791. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  78792. var indicesInit = function (i) {
  78793. if (!indices) {
  78794. return;
  78795. }
  78796. var offset = (submesh.indexStart / 3) + i;
  78797. var pos = (offset * 3);
  78798. var i0 = indices[pos + 0];
  78799. var i1 = indices[pos + 1];
  78800. var i2 = indices[pos + 2];
  78801. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  78802. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  78803. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  78804. var triangle = new DecimationTriangle([v0, v1, v2]);
  78805. triangle.originalOffset = pos;
  78806. _this.triangles.push(triangle);
  78807. };
  78808. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  78809. _this.init(callback);
  78810. });
  78811. });
  78812. };
  78813. QuadraticErrorSimplification.prototype.init = function (callback) {
  78814. var _this = this;
  78815. var triangleInit1 = function (i) {
  78816. var t = _this.triangles[i];
  78817. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  78818. for (var j = 0; j < 3; j++) {
  78819. 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))));
  78820. }
  78821. };
  78822. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  78823. var triangleInit2 = function (i) {
  78824. var t = _this.triangles[i];
  78825. for (var j = 0; j < 3; ++j) {
  78826. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  78827. }
  78828. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78829. };
  78830. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  78831. callback();
  78832. });
  78833. });
  78834. };
  78835. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  78836. var newTriangles = [];
  78837. var i;
  78838. for (i = 0; i < this.vertices.length; ++i) {
  78839. this.vertices[i].triangleCount = 0;
  78840. }
  78841. var t;
  78842. var j;
  78843. for (i = 0; i < this.triangles.length; ++i) {
  78844. if (!this.triangles[i].deleted) {
  78845. t = this.triangles[i];
  78846. for (j = 0; j < 3; ++j) {
  78847. t.vertices[j].triangleCount = 1;
  78848. }
  78849. newTriangles.push(t);
  78850. }
  78851. }
  78852. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  78853. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  78854. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  78855. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  78856. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  78857. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78858. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  78859. var vertexCount = 0;
  78860. for (i = 0; i < this.vertices.length; ++i) {
  78861. var vertex = this.vertices[i];
  78862. vertex.id = vertexCount;
  78863. if (vertex.triangleCount) {
  78864. vertex.originalOffsets.forEach(function (originalOffset) {
  78865. if (!normalData) {
  78866. return;
  78867. }
  78868. newPositionData.push(vertex.position.x);
  78869. newPositionData.push(vertex.position.y);
  78870. newPositionData.push(vertex.position.z);
  78871. newNormalData.push(normalData[originalOffset * 3]);
  78872. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  78873. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  78874. if (uvs && uvs.length) {
  78875. newUVsData.push(uvs[(originalOffset * 2)]);
  78876. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  78877. }
  78878. else if (colorsData && colorsData.length) {
  78879. newColorsData.push(colorsData[(originalOffset * 4)]);
  78880. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  78881. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  78882. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  78883. }
  78884. ++vertexCount;
  78885. });
  78886. }
  78887. }
  78888. var startingIndex = this._reconstructedMesh.getTotalIndices();
  78889. var startingVertex = this._reconstructedMesh.getTotalVertices();
  78890. var submeshesArray = this._reconstructedMesh.subMeshes;
  78891. this._reconstructedMesh.subMeshes = [];
  78892. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  78893. var originalIndices = this._mesh.getIndices();
  78894. for (i = 0; i < newTriangles.length; ++i) {
  78895. t = newTriangles[i]; //now get the new referencing point for each vertex
  78896. [0, 1, 2].forEach(function (idx) {
  78897. var id = originalIndices[t.originalOffset + idx];
  78898. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  78899. if (offset < 0)
  78900. offset = 0;
  78901. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  78902. });
  78903. }
  78904. //overwriting the old vertex buffers and indices.
  78905. this._reconstructedMesh.setIndices(newIndicesArray);
  78906. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  78907. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  78908. if (newUVsData.length > 0)
  78909. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  78910. if (newColorsData.length > 0)
  78911. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  78912. //create submesh
  78913. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  78914. if (submeshIndex > 0) {
  78915. this._reconstructedMesh.subMeshes = [];
  78916. submeshesArray.forEach(function (submesh) {
  78917. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  78918. });
  78919. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  78920. }
  78921. };
  78922. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  78923. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  78924. this._reconstructedMesh.material = this._mesh.material;
  78925. this._reconstructedMesh.parent = this._mesh.parent;
  78926. this._reconstructedMesh.isVisible = false;
  78927. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  78928. };
  78929. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  78930. for (var i = 0; i < vertex1.triangleCount; ++i) {
  78931. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  78932. if (t.deleted)
  78933. continue;
  78934. var s = this.references[vertex1.triangleStart + i].vertexId;
  78935. var v1 = t.vertices[(s + 1) % 3];
  78936. var v2 = t.vertices[(s + 2) % 3];
  78937. if ((v1 === vertex2 || v2 === vertex2)) {
  78938. deletedArray[i] = true;
  78939. delTr.push(t);
  78940. continue;
  78941. }
  78942. var d1 = v1.position.subtract(point);
  78943. d1 = d1.normalize();
  78944. var d2 = v2.position.subtract(point);
  78945. d2 = d2.normalize();
  78946. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  78947. return true;
  78948. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  78949. deletedArray[i] = false;
  78950. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  78951. return true;
  78952. }
  78953. return false;
  78954. };
  78955. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  78956. var newDeleted = deletedTriangles;
  78957. for (var i = 0; i < vertex.triangleCount; ++i) {
  78958. var ref = this.references[vertex.triangleStart + i];
  78959. var t = this.triangles[ref.triangleId];
  78960. if (t.deleted)
  78961. continue;
  78962. if (deletedArray[i] && t.deletePending) {
  78963. t.deleted = true;
  78964. newDeleted++;
  78965. continue;
  78966. }
  78967. t.vertices[ref.vertexId] = origVertex;
  78968. t.isDirty = true;
  78969. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  78970. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  78971. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  78972. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78973. this.references.push(ref);
  78974. }
  78975. return newDeleted;
  78976. };
  78977. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  78978. for (var i = 0; i < this.vertices.length; ++i) {
  78979. var vCount = [];
  78980. var vId = [];
  78981. var v = this.vertices[i];
  78982. var j;
  78983. for (j = 0; j < v.triangleCount; ++j) {
  78984. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  78985. for (var ii = 0; ii < 3; ii++) {
  78986. var ofs = 0;
  78987. var vv = triangle.vertices[ii];
  78988. while (ofs < vCount.length) {
  78989. if (vId[ofs] === vv.id)
  78990. break;
  78991. ++ofs;
  78992. }
  78993. if (ofs === vCount.length) {
  78994. vCount.push(1);
  78995. vId.push(vv.id);
  78996. }
  78997. else {
  78998. vCount[ofs]++;
  78999. }
  79000. }
  79001. }
  79002. for (j = 0; j < vCount.length; ++j) {
  79003. if (vCount[j] === 1) {
  79004. this.vertices[vId[j]].isBorder = true;
  79005. }
  79006. else {
  79007. this.vertices[vId[j]].isBorder = false;
  79008. }
  79009. }
  79010. }
  79011. };
  79012. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  79013. if (identifyBorders === void 0) { identifyBorders = false; }
  79014. var i;
  79015. if (!identifyBorders) {
  79016. var newTrianglesVector = [];
  79017. for (i = 0; i < this.triangles.length; ++i) {
  79018. if (!this.triangles[i].deleted) {
  79019. newTrianglesVector.push(this.triangles[i]);
  79020. }
  79021. }
  79022. this.triangles = newTrianglesVector;
  79023. }
  79024. for (i = 0; i < this.vertices.length; ++i) {
  79025. this.vertices[i].triangleCount = 0;
  79026. this.vertices[i].triangleStart = 0;
  79027. }
  79028. var t;
  79029. var j;
  79030. var v;
  79031. for (i = 0; i < this.triangles.length; ++i) {
  79032. t = this.triangles[i];
  79033. for (j = 0; j < 3; ++j) {
  79034. v = t.vertices[j];
  79035. v.triangleCount++;
  79036. }
  79037. }
  79038. var tStart = 0;
  79039. for (i = 0; i < this.vertices.length; ++i) {
  79040. this.vertices[i].triangleStart = tStart;
  79041. tStart += this.vertices[i].triangleCount;
  79042. this.vertices[i].triangleCount = 0;
  79043. }
  79044. var newReferences = new Array(this.triangles.length * 3);
  79045. for (i = 0; i < this.triangles.length; ++i) {
  79046. t = this.triangles[i];
  79047. for (j = 0; j < 3; ++j) {
  79048. v = t.vertices[j];
  79049. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  79050. v.triangleCount++;
  79051. }
  79052. }
  79053. this.references = newReferences;
  79054. if (identifyBorders) {
  79055. this.identifyBorder();
  79056. }
  79057. };
  79058. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  79059. var x = point.x;
  79060. var y = point.y;
  79061. var z = point.z;
  79062. 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
  79063. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  79064. };
  79065. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  79066. var q = vertex1.q.add(vertex2.q);
  79067. var border = vertex1.isBorder && vertex2.isBorder;
  79068. var error = 0;
  79069. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  79070. if (qDet !== 0 && !border) {
  79071. if (!pointResult) {
  79072. pointResult = BABYLON.Vector3.Zero();
  79073. }
  79074. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  79075. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  79076. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  79077. error = this.vertexError(q, pointResult);
  79078. }
  79079. else {
  79080. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  79081. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  79082. var error1 = this.vertexError(q, vertex1.position);
  79083. var error2 = this.vertexError(q, vertex2.position);
  79084. var error3 = this.vertexError(q, p3);
  79085. error = Math.min(error1, error2, error3);
  79086. if (error === error1) {
  79087. if (pointResult) {
  79088. pointResult.copyFrom(vertex1.position);
  79089. }
  79090. }
  79091. else if (error === error2) {
  79092. if (pointResult) {
  79093. pointResult.copyFrom(vertex2.position);
  79094. }
  79095. }
  79096. else {
  79097. if (pointResult) {
  79098. pointResult.copyFrom(p3);
  79099. }
  79100. }
  79101. }
  79102. return error;
  79103. };
  79104. return QuadraticErrorSimplification;
  79105. }());
  79106. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  79107. })(BABYLON || (BABYLON = {}));
  79108. //# sourceMappingURL=babylon.meshSimplification.js.map
  79109. var BABYLON;
  79110. (function (BABYLON) {
  79111. var MeshLODLevel = /** @class */ (function () {
  79112. function MeshLODLevel(distance, mesh) {
  79113. this.distance = distance;
  79114. this.mesh = mesh;
  79115. }
  79116. return MeshLODLevel;
  79117. }());
  79118. BABYLON.MeshLODLevel = MeshLODLevel;
  79119. })(BABYLON || (BABYLON = {}));
  79120. //# sourceMappingURL=babylon.meshLODLevel.js.map
  79121. var BABYLON;
  79122. (function (BABYLON) {
  79123. /**
  79124. * Defines the root class used to create scene optimization to use with SceneOptimizer
  79125. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79126. */
  79127. var SceneOptimization = /** @class */ (function () {
  79128. /**
  79129. * Creates the SceneOptimization object
  79130. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79131. * @param desc defines the description associated with the optimization
  79132. */
  79133. function SceneOptimization(
  79134. /**
  79135. * Defines the priority of this optimization (0 by default which means first in the list)
  79136. */
  79137. priority) {
  79138. if (priority === void 0) { priority = 0; }
  79139. this.priority = priority;
  79140. }
  79141. /**
  79142. * Gets a string describing the action executed by the current optimization
  79143. * @returns description string
  79144. */
  79145. SceneOptimization.prototype.getDescription = function () {
  79146. return "";
  79147. };
  79148. /**
  79149. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79150. * @param scene defines the current scene where to apply this optimization
  79151. * @param optimizer defines the current optimizer
  79152. * @returns true if everything that can be done was applied
  79153. */
  79154. SceneOptimization.prototype.apply = function (scene, optimizer) {
  79155. return true;
  79156. };
  79157. ;
  79158. return SceneOptimization;
  79159. }());
  79160. BABYLON.SceneOptimization = SceneOptimization;
  79161. /**
  79162. * Defines an optimization used to reduce the size of render target textures
  79163. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79164. */
  79165. var TextureOptimization = /** @class */ (function (_super) {
  79166. __extends(TextureOptimization, _super);
  79167. /**
  79168. * Creates the TextureOptimization object
  79169. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79170. * @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
  79171. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  79172. */
  79173. function TextureOptimization(
  79174. /**
  79175. * Defines the priority of this optimization (0 by default which means first in the list)
  79176. */
  79177. priority,
  79178. /**
  79179. * 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
  79180. */
  79181. maximumSize,
  79182. /**
  79183. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  79184. */
  79185. step) {
  79186. if (priority === void 0) { priority = 0; }
  79187. if (maximumSize === void 0) { maximumSize = 1024; }
  79188. if (step === void 0) { step = 0.5; }
  79189. var _this = _super.call(this, priority) || this;
  79190. _this.priority = priority;
  79191. _this.maximumSize = maximumSize;
  79192. _this.step = step;
  79193. return _this;
  79194. }
  79195. /**
  79196. * Gets a string describing the action executed by the current optimization
  79197. * @returns description string
  79198. */
  79199. TextureOptimization.prototype.getDescription = function () {
  79200. return "Reducing render target texture size to " + this.maximumSize;
  79201. };
  79202. /**
  79203. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79204. * @param scene defines the current scene where to apply this optimization
  79205. * @param optimizer defines the current optimizer
  79206. * @returns true if everything that can be done was applied
  79207. */
  79208. TextureOptimization.prototype.apply = function (scene, optimizer) {
  79209. var allDone = true;
  79210. for (var index = 0; index < scene.textures.length; index++) {
  79211. var texture = scene.textures[index];
  79212. if (!texture.canRescale || texture.getContext) {
  79213. continue;
  79214. }
  79215. var currentSize = texture.getSize();
  79216. var maxDimension = Math.max(currentSize.width, currentSize.height);
  79217. if (maxDimension > this.maximumSize) {
  79218. texture.scale(this.step);
  79219. allDone = false;
  79220. }
  79221. }
  79222. return allDone;
  79223. };
  79224. return TextureOptimization;
  79225. }(SceneOptimization));
  79226. BABYLON.TextureOptimization = TextureOptimization;
  79227. /**
  79228. * Defines an optimization used to increase or decrease the rendering resolution
  79229. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79230. */
  79231. var HardwareScalingOptimization = /** @class */ (function (_super) {
  79232. __extends(HardwareScalingOptimization, _super);
  79233. /**
  79234. * Creates the HardwareScalingOptimization object
  79235. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79236. * @param maximumScale defines the maximum scale to use (2 by default)
  79237. * @param step defines the step to use between two passes (0.5 by default)
  79238. */
  79239. function HardwareScalingOptimization(
  79240. /**
  79241. * Defines the priority of this optimization (0 by default which means first in the list)
  79242. */
  79243. priority,
  79244. /**
  79245. * Defines the maximum scale to use (2 by default)
  79246. */
  79247. maximumScale,
  79248. /**
  79249. * Defines the step to use between two passes (0.5 by default)
  79250. */
  79251. step) {
  79252. if (priority === void 0) { priority = 0; }
  79253. if (maximumScale === void 0) { maximumScale = 2; }
  79254. if (step === void 0) { step = 0.25; }
  79255. var _this = _super.call(this, priority) || this;
  79256. _this.priority = priority;
  79257. _this.maximumScale = maximumScale;
  79258. _this.step = step;
  79259. _this._currentScale = -1;
  79260. _this._directionOffset = 1;
  79261. return _this;
  79262. }
  79263. /**
  79264. * Gets a string describing the action executed by the current optimization
  79265. * @return description string
  79266. */
  79267. HardwareScalingOptimization.prototype.getDescription = function () {
  79268. return "Setting hardware scaling level to " + this._currentScale;
  79269. };
  79270. /**
  79271. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79272. * @param scene defines the current scene where to apply this optimization
  79273. * @param optimizer defines the current optimizer
  79274. * @returns true if everything that can be done was applied
  79275. */
  79276. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  79277. if (this._currentScale === -1) {
  79278. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  79279. if (this._currentScale > this.maximumScale) {
  79280. this._directionOffset = -1;
  79281. }
  79282. }
  79283. this._currentScale += this._directionOffset * this.step;
  79284. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  79285. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  79286. };
  79287. ;
  79288. return HardwareScalingOptimization;
  79289. }(SceneOptimization));
  79290. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  79291. /**
  79292. * Defines an optimization used to remove shadows
  79293. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79294. */
  79295. var ShadowsOptimization = /** @class */ (function (_super) {
  79296. __extends(ShadowsOptimization, _super);
  79297. function ShadowsOptimization() {
  79298. return _super !== null && _super.apply(this, arguments) || this;
  79299. }
  79300. /**
  79301. * Gets a string describing the action executed by the current optimization
  79302. * @return description string
  79303. */
  79304. ShadowsOptimization.prototype.getDescription = function () {
  79305. return "Turning shadows on/off";
  79306. };
  79307. /**
  79308. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79309. * @param scene defines the current scene where to apply this optimization
  79310. * @param optimizer defines the current optimizer
  79311. * @returns true if everything that can be done was applied
  79312. */
  79313. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  79314. scene.shadowsEnabled = optimizer.isInImprovementMode;
  79315. return true;
  79316. };
  79317. ;
  79318. return ShadowsOptimization;
  79319. }(SceneOptimization));
  79320. BABYLON.ShadowsOptimization = ShadowsOptimization;
  79321. /**
  79322. * Defines an optimization used to turn post-processes off
  79323. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79324. */
  79325. var PostProcessesOptimization = /** @class */ (function (_super) {
  79326. __extends(PostProcessesOptimization, _super);
  79327. function PostProcessesOptimization() {
  79328. return _super !== null && _super.apply(this, arguments) || this;
  79329. }
  79330. /**
  79331. * Gets a string describing the action executed by the current optimization
  79332. * @return description string
  79333. */
  79334. PostProcessesOptimization.prototype.getDescription = function () {
  79335. return "Turning post-processes on/off";
  79336. };
  79337. /**
  79338. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79339. * @param scene defines the current scene where to apply this optimization
  79340. * @param optimizer defines the current optimizer
  79341. * @returns true if everything that can be done was applied
  79342. */
  79343. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  79344. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  79345. return true;
  79346. };
  79347. ;
  79348. return PostProcessesOptimization;
  79349. }(SceneOptimization));
  79350. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  79351. /**
  79352. * Defines an optimization used to turn lens flares off
  79353. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79354. */
  79355. var LensFlaresOptimization = /** @class */ (function (_super) {
  79356. __extends(LensFlaresOptimization, _super);
  79357. function LensFlaresOptimization() {
  79358. return _super !== null && _super.apply(this, arguments) || this;
  79359. }
  79360. /**
  79361. * Gets a string describing the action executed by the current optimization
  79362. * @return description string
  79363. */
  79364. LensFlaresOptimization.prototype.getDescription = function () {
  79365. return "Turning lens flares on/off";
  79366. };
  79367. /**
  79368. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79369. * @param scene defines the current scene where to apply this optimization
  79370. * @param optimizer defines the current optimizer
  79371. * @returns true if everything that can be done was applied
  79372. */
  79373. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  79374. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  79375. return true;
  79376. };
  79377. ;
  79378. return LensFlaresOptimization;
  79379. }(SceneOptimization));
  79380. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  79381. /**
  79382. * Defines an optimization based on user defined callback.
  79383. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79384. */
  79385. var CustomOptimization = /** @class */ (function (_super) {
  79386. __extends(CustomOptimization, _super);
  79387. function CustomOptimization() {
  79388. return _super !== null && _super.apply(this, arguments) || this;
  79389. }
  79390. /**
  79391. * Gets a string describing the action executed by the current optimization
  79392. * @returns description string
  79393. */
  79394. CustomOptimization.prototype.getDescription = function () {
  79395. if (this.onGetDescription) {
  79396. return this.onGetDescription();
  79397. }
  79398. return "Running user defined callback";
  79399. };
  79400. /**
  79401. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79402. * @param scene defines the current scene where to apply this optimization
  79403. * @param optimizer defines the current optimizer
  79404. * @returns true if everything that can be done was applied
  79405. */
  79406. CustomOptimization.prototype.apply = function (scene, optimizer) {
  79407. if (this.onApply) {
  79408. return this.onApply(scene, optimizer);
  79409. }
  79410. return true;
  79411. };
  79412. ;
  79413. return CustomOptimization;
  79414. }(SceneOptimization));
  79415. BABYLON.CustomOptimization = CustomOptimization;
  79416. /**
  79417. * Defines an optimization used to turn particles off
  79418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79419. */
  79420. var ParticlesOptimization = /** @class */ (function (_super) {
  79421. __extends(ParticlesOptimization, _super);
  79422. function ParticlesOptimization() {
  79423. return _super !== null && _super.apply(this, arguments) || this;
  79424. }
  79425. /**
  79426. * Gets a string describing the action executed by the current optimization
  79427. * @return description string
  79428. */
  79429. ParticlesOptimization.prototype.getDescription = function () {
  79430. return "Turning particles on/off";
  79431. };
  79432. /**
  79433. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79434. * @param scene defines the current scene where to apply this optimization
  79435. * @param optimizer defines the current optimizer
  79436. * @returns true if everything that can be done was applied
  79437. */
  79438. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  79439. scene.particlesEnabled = optimizer.isInImprovementMode;
  79440. return true;
  79441. };
  79442. ;
  79443. return ParticlesOptimization;
  79444. }(SceneOptimization));
  79445. BABYLON.ParticlesOptimization = ParticlesOptimization;
  79446. /**
  79447. * Defines an optimization used to turn render targets off
  79448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79449. */
  79450. var RenderTargetsOptimization = /** @class */ (function (_super) {
  79451. __extends(RenderTargetsOptimization, _super);
  79452. function RenderTargetsOptimization() {
  79453. return _super !== null && _super.apply(this, arguments) || this;
  79454. }
  79455. /**
  79456. * Gets a string describing the action executed by the current optimization
  79457. * @return description string
  79458. */
  79459. RenderTargetsOptimization.prototype.getDescription = function () {
  79460. return "Turning render targets off";
  79461. };
  79462. /**
  79463. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79464. * @param scene defines the current scene where to apply this optimization
  79465. * @param optimizer defines the current optimizer
  79466. * @returns true if everything that can be done was applied
  79467. */
  79468. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  79469. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  79470. return true;
  79471. };
  79472. ;
  79473. return RenderTargetsOptimization;
  79474. }(SceneOptimization));
  79475. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  79476. /**
  79477. * Defines an optimization used to merge meshes with compatible materials
  79478. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79479. */
  79480. var MergeMeshesOptimization = /** @class */ (function (_super) {
  79481. __extends(MergeMeshesOptimization, _super);
  79482. function MergeMeshesOptimization() {
  79483. var _this = _super !== null && _super.apply(this, arguments) || this;
  79484. _this._canBeMerged = function (abstractMesh) {
  79485. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  79486. return false;
  79487. }
  79488. var mesh = abstractMesh;
  79489. if (!mesh.isVisible || !mesh.isEnabled()) {
  79490. return false;
  79491. }
  79492. if (mesh.instances.length > 0) {
  79493. return false;
  79494. }
  79495. if (mesh.skeleton || mesh.hasLODLevels) {
  79496. return false;
  79497. }
  79498. if (mesh.parent) {
  79499. return false;
  79500. }
  79501. return true;
  79502. };
  79503. return _this;
  79504. }
  79505. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  79506. /**
  79507. * Gets or sets a boolean which defines if optimization octree has to be updated
  79508. */
  79509. get: function () {
  79510. return MergeMeshesOptimization._UpdateSelectionTree;
  79511. },
  79512. /**
  79513. * Gets or sets a boolean which defines if optimization octree has to be updated
  79514. */
  79515. set: function (value) {
  79516. MergeMeshesOptimization._UpdateSelectionTree = value;
  79517. },
  79518. enumerable: true,
  79519. configurable: true
  79520. });
  79521. /**
  79522. * Gets a string describing the action executed by the current optimization
  79523. * @return description string
  79524. */
  79525. MergeMeshesOptimization.prototype.getDescription = function () {
  79526. return "Merging similar meshes together";
  79527. };
  79528. /**
  79529. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79530. * @param scene defines the current scene where to apply this optimization
  79531. * @param optimizer defines the current optimizer
  79532. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  79533. * @returns true if everything that can be done was applied
  79534. */
  79535. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  79536. var globalPool = scene.meshes.slice(0);
  79537. var globalLength = globalPool.length;
  79538. for (var index = 0; index < globalLength; index++) {
  79539. var currentPool = new Array();
  79540. var current = globalPool[index];
  79541. // Checks
  79542. if (!this._canBeMerged(current)) {
  79543. continue;
  79544. }
  79545. currentPool.push(current);
  79546. // Find compatible meshes
  79547. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  79548. var otherMesh = globalPool[subIndex];
  79549. if (!this._canBeMerged(otherMesh)) {
  79550. continue;
  79551. }
  79552. if (otherMesh.material !== current.material) {
  79553. continue;
  79554. }
  79555. if (otherMesh.checkCollisions !== current.checkCollisions) {
  79556. continue;
  79557. }
  79558. currentPool.push(otherMesh);
  79559. globalLength--;
  79560. globalPool.splice(subIndex, 1);
  79561. subIndex--;
  79562. }
  79563. if (currentPool.length < 2) {
  79564. continue;
  79565. }
  79566. // Merge meshes
  79567. BABYLON.Mesh.MergeMeshes(currentPool);
  79568. }
  79569. if (updateSelectionTree != undefined) {
  79570. if (updateSelectionTree) {
  79571. scene.createOrUpdateSelectionOctree();
  79572. }
  79573. }
  79574. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  79575. scene.createOrUpdateSelectionOctree();
  79576. }
  79577. return true;
  79578. };
  79579. ;
  79580. MergeMeshesOptimization._UpdateSelectionTree = false;
  79581. return MergeMeshesOptimization;
  79582. }(SceneOptimization));
  79583. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  79584. /**
  79585. * Defines a list of options used by SceneOptimizer
  79586. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79587. */
  79588. var SceneOptimizerOptions = /** @class */ (function () {
  79589. /**
  79590. * Creates a new list of options used by SceneOptimizer
  79591. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  79592. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  79593. */
  79594. function SceneOptimizerOptions(
  79595. /**
  79596. * Defines the target frame rate to reach (60 by default)
  79597. */
  79598. targetFrameRate,
  79599. /**
  79600. * Defines the interval between two checkes (2000ms by default)
  79601. */
  79602. trackerDuration) {
  79603. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  79604. if (trackerDuration === void 0) { trackerDuration = 2000; }
  79605. this.targetFrameRate = targetFrameRate;
  79606. this.trackerDuration = trackerDuration;
  79607. /**
  79608. * Gets the list of optimizations to apply
  79609. */
  79610. this.optimizations = new Array();
  79611. }
  79612. /**
  79613. * Add a new optimization
  79614. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  79615. * @returns the current SceneOptimizerOptions
  79616. */
  79617. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  79618. this.optimizations.push(optimization);
  79619. return this;
  79620. };
  79621. /**
  79622. * Add a new custom optimization
  79623. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  79624. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  79625. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79626. * @returns the current SceneOptimizerOptions
  79627. */
  79628. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  79629. if (priority === void 0) { priority = 0; }
  79630. var optimization = new CustomOptimization(priority);
  79631. optimization.onApply = onApply;
  79632. optimization.onGetDescription = onGetDescription;
  79633. this.optimizations.push(optimization);
  79634. return this;
  79635. };
  79636. /**
  79637. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  79638. * @param targetFrameRate defines the target frame rate (60 by default)
  79639. * @returns a SceneOptimizerOptions object
  79640. */
  79641. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  79642. var result = new SceneOptimizerOptions(targetFrameRate);
  79643. var priority = 0;
  79644. result.addOptimization(new MergeMeshesOptimization(priority));
  79645. result.addOptimization(new ShadowsOptimization(priority));
  79646. result.addOptimization(new LensFlaresOptimization(priority));
  79647. // Next priority
  79648. priority++;
  79649. result.addOptimization(new PostProcessesOptimization(priority));
  79650. result.addOptimization(new ParticlesOptimization(priority));
  79651. // Next priority
  79652. priority++;
  79653. result.addOptimization(new TextureOptimization(priority, 1024));
  79654. return result;
  79655. };
  79656. /**
  79657. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  79658. * @param targetFrameRate defines the target frame rate (60 by default)
  79659. * @returns a SceneOptimizerOptions object
  79660. */
  79661. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  79662. var result = new SceneOptimizerOptions(targetFrameRate);
  79663. var priority = 0;
  79664. result.addOptimization(new MergeMeshesOptimization(priority));
  79665. result.addOptimization(new ShadowsOptimization(priority));
  79666. result.addOptimization(new LensFlaresOptimization(priority));
  79667. // Next priority
  79668. priority++;
  79669. result.addOptimization(new PostProcessesOptimization(priority));
  79670. result.addOptimization(new ParticlesOptimization(priority));
  79671. // Next priority
  79672. priority++;
  79673. result.addOptimization(new TextureOptimization(priority, 512));
  79674. // Next priority
  79675. priority++;
  79676. result.addOptimization(new RenderTargetsOptimization(priority));
  79677. // Next priority
  79678. priority++;
  79679. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  79680. return result;
  79681. };
  79682. /**
  79683. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  79684. * @param targetFrameRate defines the target frame rate (60 by default)
  79685. * @returns a SceneOptimizerOptions object
  79686. */
  79687. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  79688. var result = new SceneOptimizerOptions(targetFrameRate);
  79689. var priority = 0;
  79690. result.addOptimization(new MergeMeshesOptimization(priority));
  79691. result.addOptimization(new ShadowsOptimization(priority));
  79692. result.addOptimization(new LensFlaresOptimization(priority));
  79693. // Next priority
  79694. priority++;
  79695. result.addOptimization(new PostProcessesOptimization(priority));
  79696. result.addOptimization(new ParticlesOptimization(priority));
  79697. // Next priority
  79698. priority++;
  79699. result.addOptimization(new TextureOptimization(priority, 256));
  79700. // Next priority
  79701. priority++;
  79702. result.addOptimization(new RenderTargetsOptimization(priority));
  79703. // Next priority
  79704. priority++;
  79705. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  79706. return result;
  79707. };
  79708. return SceneOptimizerOptions;
  79709. }());
  79710. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  79711. /**
  79712. * Class used to run optimizations in order to reach a target frame rate
  79713. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79714. */
  79715. var SceneOptimizer = /** @class */ (function () {
  79716. /**
  79717. * Creates a new SceneOptimizer
  79718. * @param scene defines the scene to work on
  79719. * @param options defines the options to use with the SceneOptimizer
  79720. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  79721. * @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)
  79722. */
  79723. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  79724. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  79725. if (improvementMode === void 0) { improvementMode = false; }
  79726. var _this = this;
  79727. this._isRunning = false;
  79728. this._currentPriorityLevel = 0;
  79729. this._targetFrameRate = 60;
  79730. this._trackerDuration = 2000;
  79731. this._currentFrameRate = 0;
  79732. this._improvementMode = false;
  79733. /**
  79734. * Defines an observable called when the optimizer reaches the target frame rate
  79735. */
  79736. this.onSuccessObservable = new BABYLON.Observable();
  79737. /**
  79738. * Defines an observable called when the optimizer enables an optimization
  79739. */
  79740. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  79741. /**
  79742. * Defines an observable called when the optimizer is not able to reach the target frame rate
  79743. */
  79744. this.onFailureObservable = new BABYLON.Observable();
  79745. if (!options) {
  79746. this._options = new SceneOptimizerOptions();
  79747. }
  79748. else {
  79749. this._options = options;
  79750. }
  79751. if (this._options.targetFrameRate) {
  79752. this._targetFrameRate = this._options.targetFrameRate;
  79753. }
  79754. if (this._options.trackerDuration) {
  79755. this._trackerDuration = this._options.trackerDuration;
  79756. }
  79757. if (autoGeneratePriorities) {
  79758. var priority = 0;
  79759. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  79760. var optim = _a[_i];
  79761. optim.priority = priority++;
  79762. }
  79763. }
  79764. this._improvementMode = improvementMode;
  79765. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79766. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  79767. _this._sceneDisposeObserver = null;
  79768. _this.dispose();
  79769. });
  79770. }
  79771. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  79772. /**
  79773. * Gets a boolean indicating if the optimizer is in improvement mode
  79774. */
  79775. get: function () {
  79776. return this._improvementMode;
  79777. },
  79778. enumerable: true,
  79779. configurable: true
  79780. });
  79781. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  79782. /**
  79783. * Gets the current priority level (0 at start)
  79784. */
  79785. get: function () {
  79786. return this._currentPriorityLevel;
  79787. },
  79788. enumerable: true,
  79789. configurable: true
  79790. });
  79791. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  79792. /**
  79793. * Gets the current frame rate checked by the SceneOptimizer
  79794. */
  79795. get: function () {
  79796. return this._currentFrameRate;
  79797. },
  79798. enumerable: true,
  79799. configurable: true
  79800. });
  79801. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  79802. /**
  79803. * Gets or sets the current target frame rate (60 by default)
  79804. */
  79805. get: function () {
  79806. return this._targetFrameRate;
  79807. },
  79808. /**
  79809. * Gets or sets the current target frame rate (60 by default)
  79810. */
  79811. set: function (value) {
  79812. this._targetFrameRate = value;
  79813. },
  79814. enumerable: true,
  79815. configurable: true
  79816. });
  79817. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  79818. /**
  79819. * Gets or sets the current interval between two checks (every 2000ms by default)
  79820. */
  79821. get: function () {
  79822. return this._trackerDuration;
  79823. },
  79824. /**
  79825. * Gets or sets the current interval between two checks (every 2000ms by default)
  79826. */
  79827. set: function (value) {
  79828. this._trackerDuration = value;
  79829. },
  79830. enumerable: true,
  79831. configurable: true
  79832. });
  79833. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  79834. /**
  79835. * Gets the list of active optimizations
  79836. */
  79837. get: function () {
  79838. return this._options.optimizations;
  79839. },
  79840. enumerable: true,
  79841. configurable: true
  79842. });
  79843. /**
  79844. * Stops the current optimizer
  79845. */
  79846. SceneOptimizer.prototype.stop = function () {
  79847. this._isRunning = false;
  79848. };
  79849. /**
  79850. * Reset the optimizer to initial step (current priority level = 0)
  79851. */
  79852. SceneOptimizer.prototype.reset = function () {
  79853. this._currentPriorityLevel = 0;
  79854. };
  79855. /**
  79856. * Start the optimizer. By default it will try to reach a specific framerate
  79857. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  79858. */
  79859. SceneOptimizer.prototype.start = function () {
  79860. var _this = this;
  79861. if (this._isRunning) {
  79862. return;
  79863. }
  79864. this._isRunning = true;
  79865. // Let's wait for the scene to be ready before running our check
  79866. this._scene.executeWhenReady(function () {
  79867. setTimeout(function () {
  79868. _this._checkCurrentState();
  79869. }, _this._trackerDuration);
  79870. });
  79871. };
  79872. SceneOptimizer.prototype._checkCurrentState = function () {
  79873. var _this = this;
  79874. if (!this._isRunning) {
  79875. return;
  79876. }
  79877. var scene = this._scene;
  79878. var options = this._options;
  79879. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  79880. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  79881. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  79882. this._isRunning = false;
  79883. this.onSuccessObservable.notifyObservers(this);
  79884. return;
  79885. }
  79886. // Apply current level of optimizations
  79887. var allDone = true;
  79888. var noOptimizationApplied = true;
  79889. for (var index = 0; index < options.optimizations.length; index++) {
  79890. var optimization = options.optimizations[index];
  79891. if (optimization.priority === this._currentPriorityLevel) {
  79892. noOptimizationApplied = false;
  79893. allDone = allDone && optimization.apply(scene, this);
  79894. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  79895. }
  79896. }
  79897. // If no optimization was applied, this is a failure :(
  79898. if (noOptimizationApplied) {
  79899. this._isRunning = false;
  79900. this.onFailureObservable.notifyObservers(this);
  79901. return;
  79902. }
  79903. // If all optimizations were done, move to next level
  79904. if (allDone) {
  79905. this._currentPriorityLevel++;
  79906. }
  79907. // Let's the system running for a specific amount of time before checking FPS
  79908. scene.executeWhenReady(function () {
  79909. setTimeout(function () {
  79910. _this._checkCurrentState();
  79911. }, _this._trackerDuration);
  79912. });
  79913. };
  79914. /**
  79915. * Release all resources
  79916. */
  79917. SceneOptimizer.prototype.dispose = function () {
  79918. this.stop();
  79919. this.onSuccessObservable.clear();
  79920. this.onFailureObservable.clear();
  79921. this.onNewOptimizationAppliedObservable.clear();
  79922. if (this._sceneDisposeObserver) {
  79923. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  79924. }
  79925. };
  79926. /**
  79927. * Helper function to create a SceneOptimizer with one single line of code
  79928. * @param scene defines the scene to work on
  79929. * @param options defines the options to use with the SceneOptimizer
  79930. * @param onSuccess defines a callback to call on success
  79931. * @param onFailure defines a callback to call on failure
  79932. * @returns the new SceneOptimizer object
  79933. */
  79934. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  79935. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  79936. if (onSuccess) {
  79937. optimizer.onSuccessObservable.add(function () {
  79938. onSuccess();
  79939. });
  79940. }
  79941. if (onFailure) {
  79942. optimizer.onFailureObservable.add(function () {
  79943. onFailure();
  79944. });
  79945. }
  79946. optimizer.start();
  79947. return optimizer;
  79948. };
  79949. return SceneOptimizer;
  79950. }());
  79951. BABYLON.SceneOptimizer = SceneOptimizer;
  79952. })(BABYLON || (BABYLON = {}));
  79953. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  79954. var BABYLON;
  79955. (function (BABYLON) {
  79956. var OutlineRenderer = /** @class */ (function () {
  79957. function OutlineRenderer(scene) {
  79958. this.zOffset = 1;
  79959. this._scene = scene;
  79960. }
  79961. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  79962. var _this = this;
  79963. if (useOverlay === void 0) { useOverlay = false; }
  79964. var scene = this._scene;
  79965. var engine = this._scene.getEngine();
  79966. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79967. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  79968. return;
  79969. }
  79970. var mesh = subMesh.getRenderingMesh();
  79971. var material = subMesh.getMaterial();
  79972. if (!material || !scene.activeCamera) {
  79973. return;
  79974. }
  79975. engine.enableEffect(this._effect);
  79976. // Logarithmic depth
  79977. if (material.useLogarithmicDepth) {
  79978. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  79979. }
  79980. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  79981. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  79982. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79983. // Bones
  79984. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79985. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79986. }
  79987. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  79988. // Alpha test
  79989. if (material && material.needAlphaTesting()) {
  79990. var alphaTexture = material.getAlphaTestTexture();
  79991. if (alphaTexture) {
  79992. this._effect.setTexture("diffuseSampler", alphaTexture);
  79993. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79994. }
  79995. }
  79996. engine.setZOffset(-this.zOffset);
  79997. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  79998. engine.setZOffset(0);
  79999. };
  80000. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  80001. var defines = [];
  80002. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80003. var mesh = subMesh.getMesh();
  80004. var material = subMesh.getMaterial();
  80005. if (material) {
  80006. // Alpha test
  80007. if (material.needAlphaTesting()) {
  80008. defines.push("#define ALPHATEST");
  80009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80010. attribs.push(BABYLON.VertexBuffer.UVKind);
  80011. defines.push("#define UV1");
  80012. }
  80013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80014. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80015. defines.push("#define UV2");
  80016. }
  80017. }
  80018. //Logarithmic depth
  80019. if (material.useLogarithmicDepth) {
  80020. defines.push("#define LOGARITHMICDEPTH");
  80021. }
  80022. }
  80023. // Bones
  80024. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80025. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80026. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80027. if (mesh.numBoneInfluencers > 4) {
  80028. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80029. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80030. }
  80031. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80032. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80033. }
  80034. else {
  80035. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80036. }
  80037. // Instances
  80038. if (useInstances) {
  80039. defines.push("#define INSTANCES");
  80040. attribs.push("world0");
  80041. attribs.push("world1");
  80042. attribs.push("world2");
  80043. attribs.push("world3");
  80044. }
  80045. // Get correct effect
  80046. var join = defines.join("\n");
  80047. if (this._cachedDefines !== join) {
  80048. this._cachedDefines = join;
  80049. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  80050. }
  80051. return this._effect.isReady();
  80052. };
  80053. return OutlineRenderer;
  80054. }());
  80055. BABYLON.OutlineRenderer = OutlineRenderer;
  80056. })(BABYLON || (BABYLON = {}));
  80057. //# sourceMappingURL=babylon.outlineRenderer.js.map
  80058. var BABYLON;
  80059. (function (BABYLON) {
  80060. var FaceAdjacencies = /** @class */ (function () {
  80061. function FaceAdjacencies() {
  80062. this.edges = new Array();
  80063. this.edgesConnectedCount = 0;
  80064. }
  80065. return FaceAdjacencies;
  80066. }());
  80067. var EdgesRenderer = /** @class */ (function () {
  80068. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  80069. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  80070. if (epsilon === void 0) { epsilon = 0.95; }
  80071. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  80072. this.edgesWidthScalerForOrthographic = 1000.0;
  80073. this.edgesWidthScalerForPerspective = 50.0;
  80074. this._linesPositions = new Array();
  80075. this._linesNormals = new Array();
  80076. this._linesIndices = new Array();
  80077. this._buffers = {};
  80078. this._checkVerticesInsteadOfIndices = false;
  80079. this._source = source;
  80080. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  80081. this._epsilon = epsilon;
  80082. this._prepareRessources();
  80083. this._generateEdgesLines();
  80084. }
  80085. EdgesRenderer.prototype._prepareRessources = function () {
  80086. if (this._lineShader) {
  80087. return;
  80088. }
  80089. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  80090. attributes: ["position", "normal"],
  80091. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  80092. });
  80093. this._lineShader.disableDepthWrite = true;
  80094. this._lineShader.backFaceCulling = false;
  80095. };
  80096. EdgesRenderer.prototype._rebuild = function () {
  80097. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  80098. if (buffer) {
  80099. buffer._rebuild();
  80100. }
  80101. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  80102. if (buffer) {
  80103. buffer._rebuild();
  80104. }
  80105. var scene = this._source.getScene();
  80106. var engine = scene.getEngine();
  80107. this._ib = engine.createIndexBuffer(this._linesIndices);
  80108. };
  80109. EdgesRenderer.prototype.dispose = function () {
  80110. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  80111. if (buffer) {
  80112. buffer.dispose();
  80113. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  80114. }
  80115. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  80116. if (buffer) {
  80117. buffer.dispose();
  80118. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  80119. }
  80120. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  80121. this._lineShader.dispose();
  80122. };
  80123. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  80124. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  80125. return 0;
  80126. }
  80127. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  80128. return 1;
  80129. }
  80130. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  80131. return 2;
  80132. }
  80133. return -1;
  80134. };
  80135. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  80136. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  80137. return 0;
  80138. }
  80139. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  80140. return 1;
  80141. }
  80142. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  80143. return 2;
  80144. }
  80145. return -1;
  80146. };
  80147. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  80148. var needToCreateLine;
  80149. if (edge === undefined) {
  80150. needToCreateLine = true;
  80151. }
  80152. else {
  80153. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  80154. needToCreateLine = dotProduct < this._epsilon;
  80155. }
  80156. if (needToCreateLine) {
  80157. var offset = this._linesPositions.length / 3;
  80158. var normal = p0.subtract(p1);
  80159. normal.normalize();
  80160. // Positions
  80161. this._linesPositions.push(p0.x);
  80162. this._linesPositions.push(p0.y);
  80163. this._linesPositions.push(p0.z);
  80164. this._linesPositions.push(p0.x);
  80165. this._linesPositions.push(p0.y);
  80166. this._linesPositions.push(p0.z);
  80167. this._linesPositions.push(p1.x);
  80168. this._linesPositions.push(p1.y);
  80169. this._linesPositions.push(p1.z);
  80170. this._linesPositions.push(p1.x);
  80171. this._linesPositions.push(p1.y);
  80172. this._linesPositions.push(p1.z);
  80173. // Normals
  80174. this._linesNormals.push(p1.x);
  80175. this._linesNormals.push(p1.y);
  80176. this._linesNormals.push(p1.z);
  80177. this._linesNormals.push(-1);
  80178. this._linesNormals.push(p1.x);
  80179. this._linesNormals.push(p1.y);
  80180. this._linesNormals.push(p1.z);
  80181. this._linesNormals.push(1);
  80182. this._linesNormals.push(p0.x);
  80183. this._linesNormals.push(p0.y);
  80184. this._linesNormals.push(p0.z);
  80185. this._linesNormals.push(-1);
  80186. this._linesNormals.push(p0.x);
  80187. this._linesNormals.push(p0.y);
  80188. this._linesNormals.push(p0.z);
  80189. this._linesNormals.push(1);
  80190. // Indices
  80191. this._linesIndices.push(offset);
  80192. this._linesIndices.push(offset + 1);
  80193. this._linesIndices.push(offset + 2);
  80194. this._linesIndices.push(offset);
  80195. this._linesIndices.push(offset + 2);
  80196. this._linesIndices.push(offset + 3);
  80197. }
  80198. };
  80199. EdgesRenderer.prototype._generateEdgesLines = function () {
  80200. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80201. var indices = this._source.getIndices();
  80202. if (!indices || !positions) {
  80203. return;
  80204. }
  80205. // First let's find adjacencies
  80206. var adjacencies = new Array();
  80207. var faceNormals = new Array();
  80208. var index;
  80209. var faceAdjacencies;
  80210. // Prepare faces
  80211. for (index = 0; index < indices.length; index += 3) {
  80212. faceAdjacencies = new FaceAdjacencies();
  80213. var p0Index = indices[index];
  80214. var p1Index = indices[index + 1];
  80215. var p2Index = indices[index + 2];
  80216. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  80217. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  80218. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  80219. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  80220. faceNormal.normalize();
  80221. faceNormals.push(faceNormal);
  80222. adjacencies.push(faceAdjacencies);
  80223. }
  80224. // Scan
  80225. for (index = 0; index < adjacencies.length; index++) {
  80226. faceAdjacencies = adjacencies[index];
  80227. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  80228. var otherFaceAdjacencies = adjacencies[otherIndex];
  80229. if (faceAdjacencies.edgesConnectedCount === 3) {
  80230. break;
  80231. }
  80232. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  80233. continue;
  80234. }
  80235. var otherP0 = indices[otherIndex * 3];
  80236. var otherP1 = indices[otherIndex * 3 + 1];
  80237. var otherP2 = indices[otherIndex * 3 + 2];
  80238. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  80239. var otherEdgeIndex = 0;
  80240. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  80241. continue;
  80242. }
  80243. switch (edgeIndex) {
  80244. case 0:
  80245. if (this._checkVerticesInsteadOfIndices) {
  80246. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80247. }
  80248. else {
  80249. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  80250. }
  80251. break;
  80252. case 1:
  80253. if (this._checkVerticesInsteadOfIndices) {
  80254. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80255. }
  80256. else {
  80257. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  80258. }
  80259. break;
  80260. case 2:
  80261. if (this._checkVerticesInsteadOfIndices) {
  80262. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80263. }
  80264. else {
  80265. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  80266. }
  80267. break;
  80268. }
  80269. if (otherEdgeIndex === -1) {
  80270. continue;
  80271. }
  80272. faceAdjacencies.edges[edgeIndex] = otherIndex;
  80273. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  80274. faceAdjacencies.edgesConnectedCount++;
  80275. otherFaceAdjacencies.edgesConnectedCount++;
  80276. if (faceAdjacencies.edgesConnectedCount === 3) {
  80277. break;
  80278. }
  80279. }
  80280. }
  80281. }
  80282. // Create lines
  80283. for (index = 0; index < adjacencies.length; index++) {
  80284. // 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
  80285. var current = adjacencies[index];
  80286. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  80287. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  80288. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  80289. }
  80290. // Merge into a single mesh
  80291. var engine = this._source.getScene().getEngine();
  80292. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  80293. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  80294. this._ib = engine.createIndexBuffer(this._linesIndices);
  80295. this._indicesCount = this._linesIndices.length;
  80296. };
  80297. EdgesRenderer.prototype.render = function () {
  80298. var scene = this._source.getScene();
  80299. if (!this._lineShader.isReady() || !scene.activeCamera) {
  80300. return;
  80301. }
  80302. var engine = scene.getEngine();
  80303. this._lineShader._preBind();
  80304. // VBOs
  80305. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  80306. scene.resetCachedMaterial();
  80307. this._lineShader.setColor4("color", this._source.edgesColor);
  80308. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  80309. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  80310. }
  80311. else {
  80312. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  80313. }
  80314. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  80315. this._lineShader.bind(this._source.getWorldMatrix());
  80316. // Draw order
  80317. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  80318. this._lineShader.unbind();
  80319. engine.setDepthWrite(true);
  80320. };
  80321. return EdgesRenderer;
  80322. }());
  80323. BABYLON.EdgesRenderer = EdgesRenderer;
  80324. })(BABYLON || (BABYLON = {}));
  80325. //# sourceMappingURL=babylon.edgesRenderer.js.map
  80326. var BABYLON;
  80327. (function (BABYLON) {
  80328. /**
  80329. * Special Glow Blur post process only blurring the alpha channel
  80330. * It enforces keeping the most luminous color in the color channel.
  80331. */
  80332. var GlowBlurPostProcess = /** @class */ (function (_super) {
  80333. __extends(GlowBlurPostProcess, _super);
  80334. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  80335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80336. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  80337. _this.direction = direction;
  80338. _this.kernel = kernel;
  80339. _this.onApplyObservable.add(function (effect) {
  80340. effect.setFloat2("screenSize", _this.width, _this.height);
  80341. effect.setVector2("direction", _this.direction);
  80342. effect.setFloat("blurWidth", _this.kernel);
  80343. });
  80344. return _this;
  80345. }
  80346. return GlowBlurPostProcess;
  80347. }(BABYLON.PostProcess));
  80348. /**
  80349. * The highlight layer Helps adding a glow effect around a mesh.
  80350. *
  80351. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  80352. * glowy meshes to your scene.
  80353. *
  80354. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  80355. */
  80356. var HighlightLayer = /** @class */ (function () {
  80357. /**
  80358. * Instantiates a new highlight Layer and references it to the scene..
  80359. * @param name The name of the layer
  80360. * @param scene The scene to use the layer in
  80361. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  80362. */
  80363. function HighlightLayer(name, scene, options) {
  80364. this.name = name;
  80365. this._vertexBuffers = {};
  80366. this._mainTextureDesiredSize = { width: 0, height: 0 };
  80367. this._meshes = {};
  80368. this._maxSize = 0;
  80369. this._shouldRender = false;
  80370. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  80371. this._excludedMeshes = {};
  80372. /**
  80373. * Specifies whether or not the inner glow is ACTIVE in the layer.
  80374. */
  80375. this.innerGlow = true;
  80376. /**
  80377. * Specifies whether or not the outer glow is ACTIVE in the layer.
  80378. */
  80379. this.outerGlow = true;
  80380. /**
  80381. * Specifies wether the highlight layer is enabled or not.
  80382. */
  80383. this.isEnabled = true;
  80384. /**
  80385. * An event triggered when the highlight layer has been disposed.
  80386. * @type {BABYLON.Observable}
  80387. */
  80388. this.onDisposeObservable = new BABYLON.Observable();
  80389. /**
  80390. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  80391. * @type {BABYLON.Observable}
  80392. */
  80393. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  80394. /**
  80395. * An event triggered when the highlight layer is being blurred.
  80396. * @type {BABYLON.Observable}
  80397. */
  80398. this.onBeforeBlurObservable = new BABYLON.Observable();
  80399. /**
  80400. * An event triggered when the highlight layer has been blurred.
  80401. * @type {BABYLON.Observable}
  80402. */
  80403. this.onAfterBlurObservable = new BABYLON.Observable();
  80404. /**
  80405. * An event triggered when the glowing blurred texture is being merged in the scene.
  80406. * @type {BABYLON.Observable}
  80407. */
  80408. this.onBeforeComposeObservable = new BABYLON.Observable();
  80409. /**
  80410. * An event triggered when the glowing blurred texture has been merged in the scene.
  80411. * @type {BABYLON.Observable}
  80412. */
  80413. this.onAfterComposeObservable = new BABYLON.Observable();
  80414. /**
  80415. * An event triggered when the highlight layer changes its size.
  80416. * @type {BABYLON.Observable}
  80417. */
  80418. this.onSizeChangedObservable = new BABYLON.Observable();
  80419. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80420. var engine = scene.getEngine();
  80421. this._engine = engine;
  80422. this._maxSize = this._engine.getCaps().maxTextureSize;
  80423. this._scene.highlightLayers.push(this);
  80424. // Warn on stencil.
  80425. if (!this._engine.isStencilEnable) {
  80426. 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 }");
  80427. }
  80428. // Adapt options
  80429. this._options = options || {
  80430. mainTextureRatio: 0.5,
  80431. blurTextureSizeRatio: 0.5,
  80432. blurHorizontalSize: 1.0,
  80433. blurVerticalSize: 1.0,
  80434. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  80435. camera: null
  80436. };
  80437. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  80438. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  80439. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  80440. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  80441. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  80442. // VBO
  80443. var vertices = [];
  80444. vertices.push(1, 1);
  80445. vertices.push(-1, 1);
  80446. vertices.push(-1, -1);
  80447. vertices.push(1, -1);
  80448. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80449. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80450. this._createIndexBuffer();
  80451. // Effect
  80452. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  80453. // Render target
  80454. this.setMainTextureSize();
  80455. // Create Textures and post processes
  80456. this.createTextureAndPostProcesses();
  80457. }
  80458. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  80459. /**
  80460. * Gets the horizontal size of the blur.
  80461. */
  80462. get: function () {
  80463. return this._horizontalBlurPostprocess.kernel;
  80464. },
  80465. /**
  80466. * Specifies the horizontal size of the blur.
  80467. */
  80468. set: function (value) {
  80469. this._horizontalBlurPostprocess.kernel = value;
  80470. },
  80471. enumerable: true,
  80472. configurable: true
  80473. });
  80474. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  80475. /**
  80476. * Gets the vertical size of the blur.
  80477. */
  80478. get: function () {
  80479. return this._verticalBlurPostprocess.kernel;
  80480. },
  80481. /**
  80482. * Specifies the vertical size of the blur.
  80483. */
  80484. set: function (value) {
  80485. this._verticalBlurPostprocess.kernel = value;
  80486. },
  80487. enumerable: true,
  80488. configurable: true
  80489. });
  80490. Object.defineProperty(HighlightLayer.prototype, "camera", {
  80491. /**
  80492. * Gets the camera attached to the layer.
  80493. */
  80494. get: function () {
  80495. return this._options.camera;
  80496. },
  80497. enumerable: true,
  80498. configurable: true
  80499. });
  80500. HighlightLayer.prototype._createIndexBuffer = function () {
  80501. var engine = this._scene.getEngine();
  80502. // Indices
  80503. var indices = [];
  80504. indices.push(0);
  80505. indices.push(1);
  80506. indices.push(2);
  80507. indices.push(0);
  80508. indices.push(2);
  80509. indices.push(3);
  80510. this._indexBuffer = engine.createIndexBuffer(indices);
  80511. };
  80512. HighlightLayer.prototype._rebuild = function () {
  80513. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80514. if (vb) {
  80515. vb._rebuild();
  80516. }
  80517. this._createIndexBuffer();
  80518. };
  80519. /**
  80520. * Creates the render target textures and post processes used in the highlight layer.
  80521. */
  80522. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  80523. var _this = this;
  80524. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  80525. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  80526. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  80527. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  80528. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  80529. width: this._mainTextureDesiredSize.width,
  80530. height: this._mainTextureDesiredSize.height
  80531. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80532. this._mainTexture.activeCamera = this._options.camera;
  80533. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80534. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80535. this._mainTexture.anisotropicFilteringLevel = 1;
  80536. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80537. this._mainTexture.renderParticles = false;
  80538. this._mainTexture.renderList = null;
  80539. this._mainTexture.ignoreCameraViewport = true;
  80540. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  80541. width: blurTextureWidth,
  80542. height: blurTextureHeight
  80543. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80544. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80545. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80546. this._blurTexture.anisotropicFilteringLevel = 16;
  80547. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80548. this._blurTexture.renderParticles = false;
  80549. this._blurTexture.ignoreCameraViewport = true;
  80550. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80551. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  80552. effect.setTexture("textureSampler", _this._mainTexture);
  80553. });
  80554. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  80555. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80556. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80557. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80558. });
  80559. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80560. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80561. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80562. });
  80563. }
  80564. else {
  80565. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80566. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80567. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80568. });
  80569. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80570. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80571. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80572. });
  80573. }
  80574. this._mainTexture.onAfterUnbindObservable.add(function () {
  80575. _this.onBeforeBlurObservable.notifyObservers(_this);
  80576. var internalTexture = _this._blurTexture.getInternalTexture();
  80577. if (internalTexture) {
  80578. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  80579. }
  80580. _this.onAfterBlurObservable.notifyObservers(_this);
  80581. });
  80582. // Custom render function
  80583. var renderSubMesh = function (subMesh) {
  80584. if (!_this._meshes) {
  80585. return;
  80586. }
  80587. var material = subMesh.getMaterial();
  80588. var mesh = subMesh.getRenderingMesh();
  80589. var scene = _this._scene;
  80590. var engine = scene.getEngine();
  80591. if (!material) {
  80592. return;
  80593. }
  80594. // Do not block in blend mode.
  80595. if (material.needAlphaBlendingForMesh(mesh)) {
  80596. return;
  80597. }
  80598. // Culling
  80599. engine.setState(material.backFaceCulling);
  80600. // Managing instances
  80601. var batch = mesh._getInstancesRenderList(subMesh._id);
  80602. if (batch.mustReturn) {
  80603. return;
  80604. }
  80605. // Excluded Mesh
  80606. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80607. return;
  80608. }
  80609. ;
  80610. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80611. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  80612. var emissiveTexture = null;
  80613. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80614. emissiveTexture = material.emissiveTexture;
  80615. }
  80616. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  80617. engine.enableEffect(_this._glowMapGenerationEffect);
  80618. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  80619. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  80620. if (highlightLayerMesh) {
  80621. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  80622. }
  80623. else {
  80624. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  80625. }
  80626. // Alpha test
  80627. if (material && material.needAlphaTesting()) {
  80628. var alphaTexture = material.getAlphaTestTexture();
  80629. if (alphaTexture) {
  80630. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  80631. var textureMatrix = alphaTexture.getTextureMatrix();
  80632. if (textureMatrix) {
  80633. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  80634. }
  80635. }
  80636. }
  80637. // Glow emissive only
  80638. if (emissiveTexture) {
  80639. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  80640. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  80641. }
  80642. // Bones
  80643. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80644. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80645. }
  80646. // Draw
  80647. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  80648. }
  80649. else {
  80650. // Need to reset refresh rate of the shadowMap
  80651. _this._mainTexture.resetRefreshCounter();
  80652. }
  80653. };
  80654. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80655. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  80656. var index;
  80657. var engine = _this._scene.getEngine();
  80658. if (depthOnlySubMeshes.length) {
  80659. engine.setColorWrite(false);
  80660. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80661. renderSubMesh(depthOnlySubMeshes.data[index]);
  80662. }
  80663. engine.setColorWrite(true);
  80664. }
  80665. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80666. renderSubMesh(opaqueSubMeshes.data[index]);
  80667. }
  80668. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80669. renderSubMesh(alphaTestSubMeshes.data[index]);
  80670. }
  80671. for (index = 0; index < transparentSubMeshes.length; index++) {
  80672. renderSubMesh(transparentSubMeshes.data[index]);
  80673. }
  80674. };
  80675. this._mainTexture.onClearObservable.add(function (engine) {
  80676. engine.clear(HighlightLayer.neutralColor, true, true, true);
  80677. });
  80678. };
  80679. /**
  80680. * Checks for the readiness of the element composing the layer.
  80681. * @param subMesh the mesh to check for
  80682. * @param useInstances specify wether or not to use instances to render the mesh
  80683. * @param emissiveTexture the associated emissive texture used to generate the glow
  80684. * @return true if ready otherwise, false
  80685. */
  80686. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  80687. var material = subMesh.getMaterial();
  80688. var mesh = subMesh.getRenderingMesh();
  80689. if (!material || !mesh || !this._meshes) {
  80690. return false;
  80691. }
  80692. var emissiveTexture = null;
  80693. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  80694. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80695. emissiveTexture = material.emissiveTexture;
  80696. }
  80697. return this._isReady(subMesh, useInstances, emissiveTexture);
  80698. };
  80699. /**
  80700. * Checks for the readiness of the element composing the layer.
  80701. * @param subMesh the mesh to check for
  80702. * @param useInstances specify wether or not to use instances to render the mesh
  80703. * @param emissiveTexture the associated emissive texture used to generate the glow
  80704. * @return true if ready otherwise, false
  80705. */
  80706. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  80707. var material = subMesh.getMaterial();
  80708. if (!material) {
  80709. return false;
  80710. }
  80711. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  80712. return false;
  80713. }
  80714. var defines = [];
  80715. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80716. var mesh = subMesh.getMesh();
  80717. var uv1 = false;
  80718. var uv2 = false;
  80719. // Alpha test
  80720. if (material && material.needAlphaTesting()) {
  80721. var alphaTexture = material.getAlphaTestTexture();
  80722. if (alphaTexture) {
  80723. defines.push("#define ALPHATEST");
  80724. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80725. alphaTexture.coordinatesIndex === 1) {
  80726. defines.push("#define DIFFUSEUV2");
  80727. uv2 = true;
  80728. }
  80729. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80730. defines.push("#define DIFFUSEUV1");
  80731. uv1 = true;
  80732. }
  80733. }
  80734. }
  80735. // Emissive
  80736. if (emissiveTexture) {
  80737. defines.push("#define EMISSIVE");
  80738. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80739. emissiveTexture.coordinatesIndex === 1) {
  80740. defines.push("#define EMISSIVEUV2");
  80741. uv2 = true;
  80742. }
  80743. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80744. defines.push("#define EMISSIVEUV1");
  80745. uv1 = true;
  80746. }
  80747. }
  80748. if (uv1) {
  80749. attribs.push(BABYLON.VertexBuffer.UVKind);
  80750. defines.push("#define UV1");
  80751. }
  80752. if (uv2) {
  80753. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80754. defines.push("#define UV2");
  80755. }
  80756. // Bones
  80757. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80758. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80759. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80760. if (mesh.numBoneInfluencers > 4) {
  80761. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80762. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80763. }
  80764. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80765. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80766. }
  80767. else {
  80768. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80769. }
  80770. // Instances
  80771. if (useInstances) {
  80772. defines.push("#define INSTANCES");
  80773. attribs.push("world0");
  80774. attribs.push("world1");
  80775. attribs.push("world2");
  80776. attribs.push("world3");
  80777. }
  80778. // Get correct effect
  80779. var join = defines.join("\n");
  80780. if (this._cachedDefines !== join) {
  80781. this._cachedDefines = join;
  80782. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  80783. }
  80784. return this._glowMapGenerationEffect.isReady();
  80785. };
  80786. /**
  80787. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  80788. */
  80789. HighlightLayer.prototype.render = function () {
  80790. var currentEffect = this._glowMapMergeEffect;
  80791. // Check
  80792. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  80793. return;
  80794. var engine = this._scene.getEngine();
  80795. this.onBeforeComposeObservable.notifyObservers(this);
  80796. // Render
  80797. engine.enableEffect(currentEffect);
  80798. engine.setState(false);
  80799. // Cache
  80800. var previousStencilBuffer = engine.getStencilBuffer();
  80801. var previousStencilFunction = engine.getStencilFunction();
  80802. var previousStencilMask = engine.getStencilMask();
  80803. var previousStencilOperationPass = engine.getStencilOperationPass();
  80804. var previousStencilOperationFail = engine.getStencilOperationFail();
  80805. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  80806. var previousAlphaMode = engine.getAlphaMode();
  80807. // Texture
  80808. currentEffect.setTexture("textureSampler", this._blurTexture);
  80809. // VBOs
  80810. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80811. // Stencil operations
  80812. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  80813. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  80814. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  80815. // Draw order
  80816. engine.setAlphaMode(this._options.alphaBlendingMode);
  80817. engine.setStencilMask(0x00);
  80818. engine.setStencilBuffer(true);
  80819. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  80820. if (this.outerGlow) {
  80821. currentEffect.setFloat("offset", 0);
  80822. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  80823. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80824. }
  80825. if (this.innerGlow) {
  80826. currentEffect.setFloat("offset", 1);
  80827. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  80828. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80829. }
  80830. // Restore Cache
  80831. engine.setStencilFunction(previousStencilFunction);
  80832. engine.setStencilMask(previousStencilMask);
  80833. engine.setAlphaMode(previousAlphaMode);
  80834. engine.setStencilBuffer(previousStencilBuffer);
  80835. engine.setStencilOperationPass(previousStencilOperationPass);
  80836. engine.setStencilOperationFail(previousStencilOperationFail);
  80837. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  80838. engine._stencilState.reset();
  80839. this.onAfterComposeObservable.notifyObservers(this);
  80840. // Handle size changes.
  80841. var size = this._mainTexture.getSize();
  80842. this.setMainTextureSize();
  80843. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  80844. // Recreate RTT and post processes on size change.
  80845. this.onSizeChangedObservable.notifyObservers(this);
  80846. this.disposeTextureAndPostProcesses();
  80847. this.createTextureAndPostProcesses();
  80848. }
  80849. };
  80850. /**
  80851. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  80852. * @param mesh The mesh to exclude from the highlight layer
  80853. */
  80854. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  80855. if (!this._excludedMeshes) {
  80856. return;
  80857. }
  80858. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80859. if (!meshExcluded) {
  80860. this._excludedMeshes[mesh.uniqueId] = {
  80861. mesh: mesh,
  80862. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  80863. mesh.getEngine().setStencilBuffer(false);
  80864. }),
  80865. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  80866. mesh.getEngine().setStencilBuffer(true);
  80867. }),
  80868. };
  80869. }
  80870. };
  80871. /**
  80872. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  80873. * @param mesh The mesh to highlight
  80874. */
  80875. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  80876. if (!this._excludedMeshes) {
  80877. return;
  80878. }
  80879. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80880. if (meshExcluded) {
  80881. if (meshExcluded.beforeRender) {
  80882. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  80883. }
  80884. if (meshExcluded.afterRender) {
  80885. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  80886. }
  80887. }
  80888. this._excludedMeshes[mesh.uniqueId] = null;
  80889. };
  80890. /**
  80891. * Determine if a given mesh will be highlighted by the current HighlightLayer
  80892. * @param mesh mesh to test
  80893. * @returns true if the mesh will be highlighted by the current HighlightLayer
  80894. */
  80895. HighlightLayer.prototype.hasMesh = function (mesh) {
  80896. if (!this._meshes) {
  80897. return false;
  80898. }
  80899. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  80900. };
  80901. /**
  80902. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  80903. * @param mesh The mesh to highlight
  80904. * @param color The color of the highlight
  80905. * @param glowEmissiveOnly Extract the glow from the emissive texture
  80906. */
  80907. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  80908. var _this = this;
  80909. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  80910. if (!this._meshes) {
  80911. return;
  80912. }
  80913. var meshHighlight = this._meshes[mesh.uniqueId];
  80914. if (meshHighlight) {
  80915. meshHighlight.color = color;
  80916. }
  80917. else {
  80918. this._meshes[mesh.uniqueId] = {
  80919. mesh: mesh,
  80920. color: color,
  80921. // Lambda required for capture due to Observable this context
  80922. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  80923. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80924. _this.defaultStencilReference(mesh);
  80925. }
  80926. else {
  80927. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  80928. }
  80929. }),
  80930. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  80931. glowEmissiveOnly: glowEmissiveOnly
  80932. };
  80933. }
  80934. this._shouldRender = true;
  80935. };
  80936. /**
  80937. * Remove a mesh from the highlight layer in order to make it stop glowing.
  80938. * @param mesh The mesh to highlight
  80939. */
  80940. HighlightLayer.prototype.removeMesh = function (mesh) {
  80941. if (!this._meshes) {
  80942. return;
  80943. }
  80944. var meshHighlight = this._meshes[mesh.uniqueId];
  80945. if (meshHighlight) {
  80946. if (meshHighlight.observerHighlight) {
  80947. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80948. }
  80949. if (meshHighlight.observerDefault) {
  80950. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80951. }
  80952. delete this._meshes[mesh.uniqueId];
  80953. }
  80954. this._shouldRender = false;
  80955. for (var meshHighlightToCheck in this._meshes) {
  80956. if (this._meshes[meshHighlightToCheck]) {
  80957. this._shouldRender = true;
  80958. break;
  80959. }
  80960. }
  80961. };
  80962. /**
  80963. * Returns true if the layer contains information to display, otherwise false.
  80964. */
  80965. HighlightLayer.prototype.shouldRender = function () {
  80966. return this.isEnabled && this._shouldRender;
  80967. };
  80968. /**
  80969. * Sets the main texture desired size which is the closest power of two
  80970. * of the engine canvas size.
  80971. */
  80972. HighlightLayer.prototype.setMainTextureSize = function () {
  80973. if (this._options.mainTextureFixedSize) {
  80974. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  80975. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  80976. }
  80977. else {
  80978. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  80979. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  80980. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  80981. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  80982. }
  80983. };
  80984. /**
  80985. * Force the stencil to the normal expected value for none glowing parts
  80986. */
  80987. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  80988. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  80989. };
  80990. /**
  80991. * Dispose only the render target textures and post process.
  80992. */
  80993. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  80994. this._blurTexture.dispose();
  80995. this._mainTexture.dispose();
  80996. this._downSamplePostprocess.dispose();
  80997. this._horizontalBlurPostprocess.dispose();
  80998. this._verticalBlurPostprocess.dispose();
  80999. };
  81000. /**
  81001. * Dispose the highlight layer and free resources.
  81002. */
  81003. HighlightLayer.prototype.dispose = function () {
  81004. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81005. if (vertexBuffer) {
  81006. vertexBuffer.dispose();
  81007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81008. }
  81009. if (this._indexBuffer) {
  81010. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81011. this._indexBuffer = null;
  81012. }
  81013. // Clean textures and post processes
  81014. this.disposeTextureAndPostProcesses();
  81015. if (this._meshes) {
  81016. // Clean mesh references
  81017. for (var id in this._meshes) {
  81018. var meshHighlight = this._meshes[id];
  81019. if (meshHighlight && meshHighlight.mesh) {
  81020. if (meshHighlight.observerHighlight) {
  81021. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  81022. }
  81023. if (meshHighlight.observerDefault) {
  81024. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  81025. }
  81026. }
  81027. }
  81028. this._meshes = null;
  81029. }
  81030. if (this._excludedMeshes) {
  81031. for (var id in this._excludedMeshes) {
  81032. var meshHighlight = this._excludedMeshes[id];
  81033. if (meshHighlight) {
  81034. if (meshHighlight.beforeRender) {
  81035. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  81036. }
  81037. if (meshHighlight.afterRender) {
  81038. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  81039. }
  81040. }
  81041. }
  81042. this._excludedMeshes = null;
  81043. }
  81044. // Remove from scene
  81045. var index = this._scene.highlightLayers.indexOf(this, 0);
  81046. if (index > -1) {
  81047. this._scene.highlightLayers.splice(index, 1);
  81048. }
  81049. // Callback
  81050. this.onDisposeObservable.notifyObservers(this);
  81051. this.onDisposeObservable.clear();
  81052. this.onBeforeRenderMainTextureObservable.clear();
  81053. this.onBeforeBlurObservable.clear();
  81054. this.onBeforeComposeObservable.clear();
  81055. this.onAfterComposeObservable.clear();
  81056. this.onSizeChangedObservable.clear();
  81057. };
  81058. /**
  81059. * The neutral color used during the preparation of the glow effect.
  81060. * This is black by default as the blend operation is a blend operation.
  81061. */
  81062. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  81063. /**
  81064. * Stencil value used for glowing meshes.
  81065. */
  81066. HighlightLayer.glowingMeshStencilReference = 0x02;
  81067. /**
  81068. * Stencil value used for the other meshes in the scene.
  81069. */
  81070. HighlightLayer.normalMeshStencilReference = 0x01;
  81071. return HighlightLayer;
  81072. }());
  81073. BABYLON.HighlightLayer = HighlightLayer;
  81074. })(BABYLON || (BABYLON = {}));
  81075. //# sourceMappingURL=babylon.highlightlayer.js.map
  81076. var BABYLON;
  81077. (function (BABYLON) {
  81078. /**
  81079. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  81080. */
  81081. var AssetTaskState;
  81082. (function (AssetTaskState) {
  81083. /**
  81084. * Initialization
  81085. */
  81086. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  81087. /**
  81088. * Running
  81089. */
  81090. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  81091. /**
  81092. * Done
  81093. */
  81094. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  81095. /**
  81096. * Error
  81097. */
  81098. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  81099. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  81100. /**
  81101. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  81102. */
  81103. var AbstractAssetTask = /** @class */ (function () {
  81104. /**
  81105. * Creates a new {BABYLON.AssetsManager}
  81106. * @param name defines the name of the task
  81107. */
  81108. function AbstractAssetTask(
  81109. /**
  81110. * Task name
  81111. */ name) {
  81112. this.name = name;
  81113. this._isCompleted = false;
  81114. this._taskState = AssetTaskState.INIT;
  81115. }
  81116. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  81117. /**
  81118. * Get if the task is completed
  81119. */
  81120. get: function () {
  81121. return this._isCompleted;
  81122. },
  81123. enumerable: true,
  81124. configurable: true
  81125. });
  81126. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  81127. /**
  81128. * Gets the current state of the task
  81129. */
  81130. get: function () {
  81131. return this._taskState;
  81132. },
  81133. enumerable: true,
  81134. configurable: true
  81135. });
  81136. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  81137. /**
  81138. * Gets the current error object (if task is in error)
  81139. */
  81140. get: function () {
  81141. return this._errorObject;
  81142. },
  81143. enumerable: true,
  81144. configurable: true
  81145. });
  81146. /**
  81147. * Internal only
  81148. * @ignore
  81149. */
  81150. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  81151. if (this._errorObject) {
  81152. return;
  81153. }
  81154. this._errorObject = {
  81155. message: message,
  81156. exception: exception
  81157. };
  81158. };
  81159. /**
  81160. * Execute the current task
  81161. * @param scene defines the scene where you want your assets to be loaded
  81162. * @param onSuccess is a callback called when the task is successfully executed
  81163. * @param onError is a callback called if an error occurs
  81164. */
  81165. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81166. var _this = this;
  81167. this._taskState = AssetTaskState.RUNNING;
  81168. this.runTask(scene, function () {
  81169. _this.onDoneCallback(onSuccess, onError);
  81170. }, function (msg, exception) {
  81171. _this.onErrorCallback(onError, msg, exception);
  81172. });
  81173. };
  81174. /**
  81175. * Execute the current task
  81176. * @param scene defines the scene where you want your assets to be loaded
  81177. * @param onSuccess is a callback called when the task is successfully executed
  81178. * @param onError is a callback called if an error occurs
  81179. */
  81180. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81181. throw new Error("runTask is not implemented");
  81182. };
  81183. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  81184. this._taskState = AssetTaskState.ERROR;
  81185. this._errorObject = {
  81186. message: message,
  81187. exception: exception
  81188. };
  81189. if (this.onError) {
  81190. this.onError(this, message, exception);
  81191. }
  81192. onError();
  81193. };
  81194. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  81195. try {
  81196. this._taskState = AssetTaskState.DONE;
  81197. this._isCompleted = true;
  81198. if (this.onSuccess) {
  81199. this.onSuccess(this);
  81200. }
  81201. onSuccess();
  81202. }
  81203. catch (e) {
  81204. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  81205. }
  81206. };
  81207. return AbstractAssetTask;
  81208. }());
  81209. BABYLON.AbstractAssetTask = AbstractAssetTask;
  81210. /**
  81211. * Class used to share progress information about assets loading
  81212. */
  81213. var AssetsProgressEvent = /** @class */ (function () {
  81214. /**
  81215. * Creates a {BABYLON.AssetsProgressEvent}
  81216. * @param remainingCount defines the number of remaining tasks to process
  81217. * @param totalCount defines the total number of tasks
  81218. * @param task defines the task that was just processed
  81219. */
  81220. function AssetsProgressEvent(remainingCount, totalCount, task) {
  81221. this.remainingCount = remainingCount;
  81222. this.totalCount = totalCount;
  81223. this.task = task;
  81224. }
  81225. return AssetsProgressEvent;
  81226. }());
  81227. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  81228. /**
  81229. * Define a task used by {BABYLON.AssetsManager} to load meshes
  81230. */
  81231. var MeshAssetTask = /** @class */ (function (_super) {
  81232. __extends(MeshAssetTask, _super);
  81233. /**
  81234. * Creates a new {BABYLON.MeshAssetTask}
  81235. * @param name defines the name of the task
  81236. * @param meshesNames defines the list of mesh's names you want to load
  81237. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  81238. * @param sceneFilename defines the filename of the scene to load from
  81239. */
  81240. function MeshAssetTask(
  81241. /**
  81242. * Defines the name of the task
  81243. */
  81244. name,
  81245. /**
  81246. * Defines the list of mesh's names you want to load
  81247. */
  81248. meshesNames,
  81249. /**
  81250. * Defines the root url to use as a base to load your meshes and associated resources
  81251. */
  81252. rootUrl,
  81253. /**
  81254. * Defines the filename of the scene to load from
  81255. */
  81256. sceneFilename) {
  81257. var _this = _super.call(this, name) || this;
  81258. _this.name = name;
  81259. _this.meshesNames = meshesNames;
  81260. _this.rootUrl = rootUrl;
  81261. _this.sceneFilename = sceneFilename;
  81262. return _this;
  81263. }
  81264. /**
  81265. * Execute the current task
  81266. * @param scene defines the scene where you want your assets to be loaded
  81267. * @param onSuccess is a callback called when the task is successfully executed
  81268. * @param onError is a callback called if an error occurs
  81269. */
  81270. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81271. var _this = this;
  81272. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  81273. _this.loadedMeshes = meshes;
  81274. _this.loadedParticleSystems = particleSystems;
  81275. _this.loadedSkeletons = skeletons;
  81276. onSuccess();
  81277. }, null, function (scene, message, exception) {
  81278. onError(message, exception);
  81279. });
  81280. };
  81281. return MeshAssetTask;
  81282. }(AbstractAssetTask));
  81283. BABYLON.MeshAssetTask = MeshAssetTask;
  81284. /**
  81285. * Define a task used by {BABYLON.AssetsManager} to load text content
  81286. */
  81287. var TextFileAssetTask = /** @class */ (function (_super) {
  81288. __extends(TextFileAssetTask, _super);
  81289. /**
  81290. * Creates a new TextFileAssetTask object
  81291. * @param name defines the name of the task
  81292. * @param url defines the location of the file to load
  81293. */
  81294. function TextFileAssetTask(
  81295. /**
  81296. * Defines the name of the task
  81297. */
  81298. name,
  81299. /**
  81300. * Defines the location of the file to load
  81301. */
  81302. url) {
  81303. var _this = _super.call(this, name) || this;
  81304. _this.name = name;
  81305. _this.url = url;
  81306. return _this;
  81307. }
  81308. /**
  81309. * Execute the current task
  81310. * @param scene defines the scene where you want your assets to be loaded
  81311. * @param onSuccess is a callback called when the task is successfully executed
  81312. * @param onError is a callback called if an error occurs
  81313. */
  81314. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81315. var _this = this;
  81316. scene._loadFile(this.url, function (data) {
  81317. _this.text = data;
  81318. onSuccess();
  81319. }, undefined, false, true, function (request, exception) {
  81320. if (request) {
  81321. onError(request.status + " " + request.statusText, exception);
  81322. }
  81323. });
  81324. };
  81325. return TextFileAssetTask;
  81326. }(AbstractAssetTask));
  81327. BABYLON.TextFileAssetTask = TextFileAssetTask;
  81328. /**
  81329. * Define a task used by {BABYLON.AssetsManager} to load binary data
  81330. */
  81331. var BinaryFileAssetTask = /** @class */ (function (_super) {
  81332. __extends(BinaryFileAssetTask, _super);
  81333. /**
  81334. * Creates a new BinaryFileAssetTask object
  81335. * @param name defines the name of the new task
  81336. * @param url defines the location of the file to load
  81337. */
  81338. function BinaryFileAssetTask(
  81339. /**
  81340. * Defines the name of the task
  81341. */
  81342. name,
  81343. /**
  81344. * Defines the location of the file to load
  81345. */
  81346. url) {
  81347. var _this = _super.call(this, name) || this;
  81348. _this.name = name;
  81349. _this.url = url;
  81350. return _this;
  81351. }
  81352. /**
  81353. * Execute the current task
  81354. * @param scene defines the scene where you want your assets to be loaded
  81355. * @param onSuccess is a callback called when the task is successfully executed
  81356. * @param onError is a callback called if an error occurs
  81357. */
  81358. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81359. var _this = this;
  81360. scene._loadFile(this.url, function (data) {
  81361. _this.data = data;
  81362. onSuccess();
  81363. }, undefined, true, true, function (request, exception) {
  81364. if (request) {
  81365. onError(request.status + " " + request.statusText, exception);
  81366. }
  81367. });
  81368. };
  81369. return BinaryFileAssetTask;
  81370. }(AbstractAssetTask));
  81371. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  81372. /**
  81373. * Define a task used by {BABYLON.AssetsManager} to load images
  81374. */
  81375. var ImageAssetTask = /** @class */ (function (_super) {
  81376. __extends(ImageAssetTask, _super);
  81377. /**
  81378. * Creates a new ImageAssetTask
  81379. * @param name defines the name of the task
  81380. * @param url defines the location of the image to load
  81381. */
  81382. function ImageAssetTask(
  81383. /**
  81384. * Defines the name of the task
  81385. */
  81386. name,
  81387. /**
  81388. * Defines the location of the image to load
  81389. */
  81390. url) {
  81391. var _this = _super.call(this, name) || this;
  81392. _this.name = name;
  81393. _this.url = url;
  81394. return _this;
  81395. }
  81396. /**
  81397. * Execute the current task
  81398. * @param scene defines the scene where you want your assets to be loaded
  81399. * @param onSuccess is a callback called when the task is successfully executed
  81400. * @param onError is a callback called if an error occurs
  81401. */
  81402. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81403. var _this = this;
  81404. var img = new Image();
  81405. BABYLON.Tools.SetCorsBehavior(this.url, img);
  81406. img.onload = function () {
  81407. _this.image = img;
  81408. onSuccess();
  81409. };
  81410. img.onerror = function (err) {
  81411. onError("Error loading image", err);
  81412. };
  81413. img.src = this.url;
  81414. };
  81415. return ImageAssetTask;
  81416. }(AbstractAssetTask));
  81417. BABYLON.ImageAssetTask = ImageAssetTask;
  81418. /**
  81419. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  81420. */
  81421. var TextureAssetTask = /** @class */ (function (_super) {
  81422. __extends(TextureAssetTask, _super);
  81423. /**
  81424. * Creates a new TextureAssetTask object
  81425. * @param name defines the name of the task
  81426. * @param url defines the location of the file to load
  81427. * @param noMipmap defines if mipmap should not be generated (default is false)
  81428. * @param invertY defines if texture must be inverted on Y axis (default is false)
  81429. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81430. */
  81431. function TextureAssetTask(
  81432. /**
  81433. * Defines the name of the task
  81434. */
  81435. name,
  81436. /**
  81437. * Defines the location of the file to load
  81438. */
  81439. url,
  81440. /**
  81441. * Defines if mipmap should not be generated (default is false)
  81442. */
  81443. noMipmap,
  81444. /**
  81445. * Defines if texture must be inverted on Y axis (default is false)
  81446. */
  81447. invertY,
  81448. /**
  81449. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81450. */
  81451. samplingMode) {
  81452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81453. var _this = _super.call(this, name) || this;
  81454. _this.name = name;
  81455. _this.url = url;
  81456. _this.noMipmap = noMipmap;
  81457. _this.invertY = invertY;
  81458. _this.samplingMode = samplingMode;
  81459. return _this;
  81460. }
  81461. /**
  81462. * Execute the current task
  81463. * @param scene defines the scene where you want your assets to be loaded
  81464. * @param onSuccess is a callback called when the task is successfully executed
  81465. * @param onError is a callback called if an error occurs
  81466. */
  81467. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81468. var onload = function () {
  81469. onSuccess();
  81470. };
  81471. var onerror = function (message, exception) {
  81472. onError(message, exception);
  81473. };
  81474. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  81475. };
  81476. return TextureAssetTask;
  81477. }(AbstractAssetTask));
  81478. BABYLON.TextureAssetTask = TextureAssetTask;
  81479. /**
  81480. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  81481. */
  81482. var CubeTextureAssetTask = /** @class */ (function (_super) {
  81483. __extends(CubeTextureAssetTask, _super);
  81484. /**
  81485. * Creates a new CubeTextureAssetTask
  81486. * @param name defines the name of the task
  81487. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81488. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81489. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81490. * @param files defines the explicit list of files (undefined by default)
  81491. */
  81492. function CubeTextureAssetTask(
  81493. /**
  81494. * Defines the name of the task
  81495. */
  81496. name,
  81497. /**
  81498. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81499. */
  81500. url,
  81501. /**
  81502. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81503. */
  81504. extensions,
  81505. /**
  81506. * Defines if mipmaps should not be generated (default is false)
  81507. */
  81508. noMipmap,
  81509. /**
  81510. * Defines the explicit list of files (undefined by default)
  81511. */
  81512. files) {
  81513. var _this = _super.call(this, name) || this;
  81514. _this.name = name;
  81515. _this.url = url;
  81516. _this.extensions = extensions;
  81517. _this.noMipmap = noMipmap;
  81518. _this.files = files;
  81519. return _this;
  81520. }
  81521. /**
  81522. * Execute the current task
  81523. * @param scene defines the scene where you want your assets to be loaded
  81524. * @param onSuccess is a callback called when the task is successfully executed
  81525. * @param onError is a callback called if an error occurs
  81526. */
  81527. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81528. var onload = function () {
  81529. onSuccess();
  81530. };
  81531. var onerror = function (message, exception) {
  81532. onError(message, exception);
  81533. };
  81534. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  81535. };
  81536. return CubeTextureAssetTask;
  81537. }(AbstractAssetTask));
  81538. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  81539. /**
  81540. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  81541. */
  81542. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  81543. __extends(HDRCubeTextureAssetTask, _super);
  81544. /**
  81545. * Creates a new HDRCubeTextureAssetTask object
  81546. * @param name defines the name of the task
  81547. * @param url defines the location of the file to load
  81548. * @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.
  81549. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81550. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81551. * @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)
  81552. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81553. */
  81554. function HDRCubeTextureAssetTask(
  81555. /**
  81556. * Defines the name of the task
  81557. */
  81558. name,
  81559. /**
  81560. * Defines the location of the file to load
  81561. */
  81562. url,
  81563. /**
  81564. * 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.
  81565. */
  81566. size,
  81567. /**
  81568. * Defines if mipmaps should not be generated (default is false)
  81569. */
  81570. noMipmap,
  81571. /**
  81572. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81573. */
  81574. generateHarmonics,
  81575. /**
  81576. * 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)
  81577. */
  81578. useInGammaSpace,
  81579. /**
  81580. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81581. */
  81582. usePMREMGenerator) {
  81583. if (noMipmap === void 0) { noMipmap = false; }
  81584. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81585. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81586. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81587. var _this = _super.call(this, name) || this;
  81588. _this.name = name;
  81589. _this.url = url;
  81590. _this.size = size;
  81591. _this.noMipmap = noMipmap;
  81592. _this.generateHarmonics = generateHarmonics;
  81593. _this.useInGammaSpace = useInGammaSpace;
  81594. _this.usePMREMGenerator = usePMREMGenerator;
  81595. return _this;
  81596. }
  81597. /**
  81598. * Execute the current task
  81599. * @param scene defines the scene where you want your assets to be loaded
  81600. * @param onSuccess is a callback called when the task is successfully executed
  81601. * @param onError is a callback called if an error occurs
  81602. */
  81603. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81604. var onload = function () {
  81605. onSuccess();
  81606. };
  81607. var onerror = function (message, exception) {
  81608. onError(message, exception);
  81609. };
  81610. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  81611. };
  81612. return HDRCubeTextureAssetTask;
  81613. }(AbstractAssetTask));
  81614. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  81615. /**
  81616. * This class can be used to easily import assets into a scene
  81617. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  81618. */
  81619. var AssetsManager = /** @class */ (function () {
  81620. /**
  81621. * Creates a new AssetsManager
  81622. * @param scene defines the scene to work on
  81623. */
  81624. function AssetsManager(scene) {
  81625. this._isLoading = false;
  81626. this._tasks = new Array();
  81627. this._waitingTasksCount = 0;
  81628. this._totalTasksCount = 0;
  81629. /**
  81630. * Observable called when all tasks are processed
  81631. */
  81632. this.onTaskSuccessObservable = new BABYLON.Observable();
  81633. /**
  81634. * Observable called when a task had an error
  81635. */
  81636. this.onTaskErrorObservable = new BABYLON.Observable();
  81637. /**
  81638. * Observable called when a task is successful
  81639. */
  81640. this.onTasksDoneObservable = new BABYLON.Observable();
  81641. /**
  81642. * Observable called when a task is done (whatever the result is)
  81643. */
  81644. this.onProgressObservable = new BABYLON.Observable();
  81645. /**
  81646. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  81647. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  81648. */
  81649. this.useDefaultLoadingScreen = true;
  81650. this._scene = scene;
  81651. }
  81652. /**
  81653. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  81654. * @param taskName defines the name of the new task
  81655. * @param meshesNames defines the name of meshes to load
  81656. * @param rootUrl defines the root url to use to locate files
  81657. * @param sceneFilename defines the filename of the scene file
  81658. * @returns a new {BABYLON.MeshAssetTask} object
  81659. */
  81660. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  81661. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  81662. this._tasks.push(task);
  81663. return task;
  81664. };
  81665. /**
  81666. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  81667. * @param taskName defines the name of the new task
  81668. * @param url defines the url of the file to load
  81669. * @returns a new {BABYLON.TextFileAssetTask} object
  81670. */
  81671. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  81672. var task = new TextFileAssetTask(taskName, url);
  81673. this._tasks.push(task);
  81674. return task;
  81675. };
  81676. /**
  81677. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  81678. * @param taskName defines the name of the new task
  81679. * @param url defines the url of the file to load
  81680. * @returns a new {BABYLON.BinaryFileAssetTask} object
  81681. */
  81682. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  81683. var task = new BinaryFileAssetTask(taskName, url);
  81684. this._tasks.push(task);
  81685. return task;
  81686. };
  81687. /**
  81688. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  81689. * @param taskName defines the name of the new task
  81690. * @param url defines the url of the file to load
  81691. * @returns a new {BABYLON.ImageAssetTask} object
  81692. */
  81693. AssetsManager.prototype.addImageTask = function (taskName, url) {
  81694. var task = new ImageAssetTask(taskName, url);
  81695. this._tasks.push(task);
  81696. return task;
  81697. };
  81698. /**
  81699. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  81700. * @param taskName defines the name of the new task
  81701. * @param url defines the url of the file to load
  81702. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81703. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  81704. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  81705. * @returns a new {BABYLON.TextureAssetTask} object
  81706. */
  81707. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  81708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81709. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  81710. this._tasks.push(task);
  81711. return task;
  81712. };
  81713. /**
  81714. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  81715. * @param taskName defines the name of the new task
  81716. * @param url defines the url of the file to load
  81717. * @param extensions defines the extension to use to load the cube map (can be null)
  81718. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81719. * @param files defines the list of files to load (can be null)
  81720. * @returns a new {BABYLON.CubeTextureAssetTask} object
  81721. */
  81722. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  81723. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  81724. this._tasks.push(task);
  81725. return task;
  81726. };
  81727. /**
  81728. *
  81729. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  81730. * @param taskName defines the name of the new task
  81731. * @param url defines the url of the file to load
  81732. * @param size defines the size you want for the cubemap (can be null)
  81733. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81734. * @param generateHarmonics defines if you want to automatically generate (true by default)
  81735. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  81736. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  81737. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  81738. */
  81739. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  81740. if (noMipmap === void 0) { noMipmap = false; }
  81741. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81742. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81743. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81744. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  81745. this._tasks.push(task);
  81746. return task;
  81747. };
  81748. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  81749. var _this = this;
  81750. this._waitingTasksCount--;
  81751. try {
  81752. if (task.taskState === AssetTaskState.DONE) {
  81753. // Let's remove successfull tasks
  81754. BABYLON.Tools.SetImmediate(function () {
  81755. var index = _this._tasks.indexOf(task);
  81756. if (index > -1) {
  81757. _this._tasks.splice(index, 1);
  81758. }
  81759. });
  81760. }
  81761. if (this.onProgress) {
  81762. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  81763. }
  81764. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  81765. }
  81766. catch (e) {
  81767. BABYLON.Tools.Error("Error running progress callbacks.");
  81768. console.log(e);
  81769. }
  81770. if (this._waitingTasksCount === 0) {
  81771. try {
  81772. if (this.onFinish) {
  81773. this.onFinish(this._tasks);
  81774. }
  81775. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81776. }
  81777. catch (e) {
  81778. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  81779. console.log(e);
  81780. }
  81781. this._isLoading = false;
  81782. this._scene.getEngine().hideLoadingUI();
  81783. }
  81784. };
  81785. AssetsManager.prototype._runTask = function (task) {
  81786. var _this = this;
  81787. var done = function () {
  81788. try {
  81789. if (_this.onTaskSuccess) {
  81790. _this.onTaskSuccess(task);
  81791. }
  81792. _this.onTaskSuccessObservable.notifyObservers(task);
  81793. _this._decreaseWaitingTasksCount(task);
  81794. }
  81795. catch (e) {
  81796. error("Error executing task success callbacks", e);
  81797. }
  81798. };
  81799. var error = function (message, exception) {
  81800. task._setErrorObject(message, exception);
  81801. if (_this.onTaskError) {
  81802. _this.onTaskError(task);
  81803. }
  81804. _this.onTaskErrorObservable.notifyObservers(task);
  81805. _this._decreaseWaitingTasksCount(task);
  81806. };
  81807. task.run(this._scene, done, error);
  81808. };
  81809. /**
  81810. * Reset the {BABYLON.AssetsManager} and remove all tasks
  81811. * @return the current instance of the {BABYLON.AssetsManager}
  81812. */
  81813. AssetsManager.prototype.reset = function () {
  81814. this._isLoading = false;
  81815. this._tasks = new Array();
  81816. return this;
  81817. };
  81818. /**
  81819. * Start the loading process
  81820. * @return the current instance of the {BABYLON.AssetsManager}
  81821. */
  81822. AssetsManager.prototype.load = function () {
  81823. if (this._isLoading) {
  81824. return this;
  81825. }
  81826. this._isLoading = true;
  81827. this._waitingTasksCount = this._tasks.length;
  81828. this._totalTasksCount = this._tasks.length;
  81829. if (this._waitingTasksCount === 0) {
  81830. if (this.onFinish) {
  81831. this.onFinish(this._tasks);
  81832. }
  81833. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81834. return this;
  81835. }
  81836. if (this.useDefaultLoadingScreen) {
  81837. this._scene.getEngine().displayLoadingUI();
  81838. }
  81839. for (var index = 0; index < this._tasks.length; index++) {
  81840. var task = this._tasks[index];
  81841. this._runTask(task);
  81842. }
  81843. return this;
  81844. };
  81845. return AssetsManager;
  81846. }());
  81847. BABYLON.AssetsManager = AssetsManager;
  81848. })(BABYLON || (BABYLON = {}));
  81849. //# sourceMappingURL=babylon.assetsManager.js.map
  81850. var BABYLON;
  81851. (function (BABYLON) {
  81852. var serializedGeometries = [];
  81853. var serializeGeometry = function (geometry, serializationGeometries) {
  81854. if (serializedGeometries[geometry.id]) {
  81855. return;
  81856. }
  81857. if (geometry.doNotSerialize) {
  81858. return;
  81859. }
  81860. if (geometry instanceof BABYLON.BoxGeometry) {
  81861. serializationGeometries.boxes.push(geometry.serialize());
  81862. }
  81863. else if (geometry instanceof BABYLON.SphereGeometry) {
  81864. serializationGeometries.spheres.push(geometry.serialize());
  81865. }
  81866. else if (geometry instanceof BABYLON.CylinderGeometry) {
  81867. serializationGeometries.cylinders.push(geometry.serialize());
  81868. }
  81869. else if (geometry instanceof BABYLON.TorusGeometry) {
  81870. serializationGeometries.toruses.push(geometry.serialize());
  81871. }
  81872. else if (geometry instanceof BABYLON.GroundGeometry) {
  81873. serializationGeometries.grounds.push(geometry.serialize());
  81874. }
  81875. else if (geometry instanceof BABYLON.Plane) {
  81876. serializationGeometries.planes.push(geometry.serialize());
  81877. }
  81878. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  81879. serializationGeometries.torusKnots.push(geometry.serialize());
  81880. }
  81881. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  81882. throw new Error("Unknown primitive type");
  81883. }
  81884. else {
  81885. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  81886. }
  81887. serializedGeometries[geometry.id] = true;
  81888. };
  81889. var serializeMesh = function (mesh, serializationScene) {
  81890. var serializationObject = {};
  81891. // Geometry
  81892. var geometry = mesh._geometry;
  81893. if (geometry) {
  81894. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  81895. // 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
  81896. serializeGeometry(geometry, serializationScene.geometries);
  81897. }
  81898. }
  81899. // Custom
  81900. if (mesh.serialize) {
  81901. mesh.serialize(serializationObject);
  81902. }
  81903. return serializationObject;
  81904. };
  81905. var finalizeSingleMesh = function (mesh, serializationObject) {
  81906. //only works if the mesh is already loaded
  81907. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81908. //serialize material
  81909. if (mesh.material) {
  81910. if (mesh.material instanceof BABYLON.StandardMaterial) {
  81911. serializationObject.materials = serializationObject.materials || [];
  81912. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81913. serializationObject.materials.push(mesh.material.serialize());
  81914. }
  81915. }
  81916. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  81917. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  81918. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81919. serializationObject.multiMaterials.push(mesh.material.serialize());
  81920. }
  81921. }
  81922. }
  81923. //serialize geometry
  81924. var geometry = mesh._geometry;
  81925. if (geometry) {
  81926. if (!serializationObject.geometries) {
  81927. serializationObject.geometries = {};
  81928. serializationObject.geometries.boxes = [];
  81929. serializationObject.geometries.spheres = [];
  81930. serializationObject.geometries.cylinders = [];
  81931. serializationObject.geometries.toruses = [];
  81932. serializationObject.geometries.grounds = [];
  81933. serializationObject.geometries.planes = [];
  81934. serializationObject.geometries.torusKnots = [];
  81935. serializationObject.geometries.vertexData = [];
  81936. }
  81937. serializeGeometry(geometry, serializationObject.geometries);
  81938. }
  81939. // Skeletons
  81940. if (mesh.skeleton) {
  81941. serializationObject.skeletons = serializationObject.skeletons || [];
  81942. serializationObject.skeletons.push(mesh.skeleton.serialize());
  81943. }
  81944. //serialize the actual mesh
  81945. serializationObject.meshes = serializationObject.meshes || [];
  81946. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81947. }
  81948. };
  81949. var SceneSerializer = /** @class */ (function () {
  81950. function SceneSerializer() {
  81951. }
  81952. SceneSerializer.ClearCache = function () {
  81953. serializedGeometries = [];
  81954. };
  81955. SceneSerializer.Serialize = function (scene) {
  81956. var serializationObject = {};
  81957. SceneSerializer.ClearCache();
  81958. // Scene
  81959. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  81960. serializationObject.autoClear = scene.autoClear;
  81961. serializationObject.clearColor = scene.clearColor.asArray();
  81962. serializationObject.ambientColor = scene.ambientColor.asArray();
  81963. serializationObject.gravity = scene.gravity.asArray();
  81964. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  81965. serializationObject.workerCollisions = scene.workerCollisions;
  81966. // Fog
  81967. if (scene.fogMode && scene.fogMode !== 0) {
  81968. serializationObject.fogMode = scene.fogMode;
  81969. serializationObject.fogColor = scene.fogColor.asArray();
  81970. serializationObject.fogStart = scene.fogStart;
  81971. serializationObject.fogEnd = scene.fogEnd;
  81972. serializationObject.fogDensity = scene.fogDensity;
  81973. }
  81974. //Physics
  81975. if (scene.isPhysicsEnabled()) {
  81976. var physicEngine = scene.getPhysicsEngine();
  81977. if (physicEngine) {
  81978. serializationObject.physicsEnabled = true;
  81979. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  81980. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  81981. }
  81982. }
  81983. // Metadata
  81984. if (scene.metadata) {
  81985. serializationObject.metadata = scene.metadata;
  81986. }
  81987. // Morph targets
  81988. serializationObject.morphTargetManagers = [];
  81989. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  81990. var abstractMesh = _a[_i];
  81991. var manager = abstractMesh.morphTargetManager;
  81992. if (manager) {
  81993. serializationObject.morphTargetManagers.push(manager.serialize());
  81994. }
  81995. }
  81996. // Lights
  81997. serializationObject.lights = [];
  81998. var index;
  81999. var light;
  82000. for (index = 0; index < scene.lights.length; index++) {
  82001. light = scene.lights[index];
  82002. if (!light.doNotSerialize) {
  82003. serializationObject.lights.push(light.serialize());
  82004. }
  82005. }
  82006. // Cameras
  82007. serializationObject.cameras = [];
  82008. for (index = 0; index < scene.cameras.length; index++) {
  82009. var camera = scene.cameras[index];
  82010. if (!camera.doNotSerialize) {
  82011. serializationObject.cameras.push(camera.serialize());
  82012. }
  82013. }
  82014. if (scene.activeCamera) {
  82015. serializationObject.activeCameraID = scene.activeCamera.id;
  82016. }
  82017. // Animations
  82018. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  82019. // Materials
  82020. serializationObject.materials = [];
  82021. serializationObject.multiMaterials = [];
  82022. var material;
  82023. for (index = 0; index < scene.materials.length; index++) {
  82024. material = scene.materials[index];
  82025. if (!material.doNotSerialize) {
  82026. serializationObject.materials.push(material.serialize());
  82027. }
  82028. }
  82029. // MultiMaterials
  82030. serializationObject.multiMaterials = [];
  82031. for (index = 0; index < scene.multiMaterials.length; index++) {
  82032. var multiMaterial = scene.multiMaterials[index];
  82033. serializationObject.multiMaterials.push(multiMaterial.serialize());
  82034. }
  82035. // Environment texture
  82036. if (scene.environmentTexture) {
  82037. serializationObject.environmentTexture = scene.environmentTexture.name;
  82038. }
  82039. // Skeletons
  82040. serializationObject.skeletons = [];
  82041. for (index = 0; index < scene.skeletons.length; index++) {
  82042. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  82043. }
  82044. // Transform nodes
  82045. serializationObject.transformNodes = [];
  82046. for (index = 0; index < scene.transformNodes.length; index++) {
  82047. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  82048. }
  82049. // Geometries
  82050. serializationObject.geometries = {};
  82051. serializationObject.geometries.boxes = [];
  82052. serializationObject.geometries.spheres = [];
  82053. serializationObject.geometries.cylinders = [];
  82054. serializationObject.geometries.toruses = [];
  82055. serializationObject.geometries.grounds = [];
  82056. serializationObject.geometries.planes = [];
  82057. serializationObject.geometries.torusKnots = [];
  82058. serializationObject.geometries.vertexData = [];
  82059. serializedGeometries = [];
  82060. var geometries = scene.getGeometries();
  82061. for (index = 0; index < geometries.length; index++) {
  82062. var geometry = geometries[index];
  82063. if (geometry.isReady()) {
  82064. serializeGeometry(geometry, serializationObject.geometries);
  82065. }
  82066. }
  82067. // Meshes
  82068. serializationObject.meshes = [];
  82069. for (index = 0; index < scene.meshes.length; index++) {
  82070. var abstractMesh = scene.meshes[index];
  82071. if (abstractMesh instanceof BABYLON.Mesh) {
  82072. var mesh = abstractMesh;
  82073. if (!mesh.doNotSerialize) {
  82074. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  82075. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  82076. }
  82077. }
  82078. }
  82079. }
  82080. // Particles Systems
  82081. serializationObject.particleSystems = [];
  82082. for (index = 0; index < scene.particleSystems.length; index++) {
  82083. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  82084. }
  82085. // Lens flares
  82086. serializationObject.lensFlareSystems = [];
  82087. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  82088. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  82089. }
  82090. // Shadows
  82091. serializationObject.shadowGenerators = [];
  82092. for (index = 0; index < scene.lights.length; index++) {
  82093. light = scene.lights[index];
  82094. var shadowGenerator = light.getShadowGenerator();
  82095. if (shadowGenerator) {
  82096. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  82097. }
  82098. }
  82099. // Action Manager
  82100. if (scene.actionManager) {
  82101. serializationObject.actions = scene.actionManager.serialize("scene");
  82102. }
  82103. // Audio
  82104. serializationObject.sounds = [];
  82105. for (index = 0; index < scene.soundTracks.length; index++) {
  82106. var soundtrack = scene.soundTracks[index];
  82107. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  82108. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  82109. }
  82110. }
  82111. return serializationObject;
  82112. };
  82113. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  82114. if (withParents === void 0) { withParents = false; }
  82115. if (withChildren === void 0) { withChildren = false; }
  82116. var serializationObject = {};
  82117. SceneSerializer.ClearCache();
  82118. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  82119. if (withParents || withChildren) {
  82120. //deliberate for loop! not for each, appended should be processed as well.
  82121. for (var i = 0; i < toSerialize.length; ++i) {
  82122. if (withChildren) {
  82123. toSerialize[i].getDescendants().forEach(function (node) {
  82124. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  82125. toSerialize.push(node);
  82126. }
  82127. });
  82128. }
  82129. //make sure the array doesn't contain the object already
  82130. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  82131. toSerialize.push(toSerialize[i].parent);
  82132. }
  82133. }
  82134. }
  82135. toSerialize.forEach(function (mesh) {
  82136. finalizeSingleMesh(mesh, serializationObject);
  82137. });
  82138. return serializationObject;
  82139. };
  82140. return SceneSerializer;
  82141. }());
  82142. BABYLON.SceneSerializer = SceneSerializer;
  82143. })(BABYLON || (BABYLON = {}));
  82144. //# sourceMappingURL=babylon.sceneSerializer.js.map
  82145. var BABYLON;
  82146. (function (BABYLON) {
  82147. var ReflectionProbe = /** @class */ (function () {
  82148. function ReflectionProbe(name, size, scene, generateMipMaps) {
  82149. if (generateMipMaps === void 0) { generateMipMaps = true; }
  82150. var _this = this;
  82151. this.name = name;
  82152. this._viewMatrix = BABYLON.Matrix.Identity();
  82153. this._target = BABYLON.Vector3.Zero();
  82154. this._add = BABYLON.Vector3.Zero();
  82155. this.invertYAxis = false;
  82156. this.position = BABYLON.Vector3.Zero();
  82157. this._scene = scene;
  82158. this._scene.reflectionProbes.push(this);
  82159. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  82160. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  82161. switch (faceIndex) {
  82162. case 0:
  82163. _this._add.copyFromFloats(1, 0, 0);
  82164. break;
  82165. case 1:
  82166. _this._add.copyFromFloats(-1, 0, 0);
  82167. break;
  82168. case 2:
  82169. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  82170. break;
  82171. case 3:
  82172. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  82173. break;
  82174. case 4:
  82175. _this._add.copyFromFloats(0, 0, 1);
  82176. break;
  82177. case 5:
  82178. _this._add.copyFromFloats(0, 0, -1);
  82179. break;
  82180. }
  82181. if (_this._attachedMesh) {
  82182. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  82183. }
  82184. _this.position.addToRef(_this._add, _this._target);
  82185. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  82186. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  82187. scene._forcedViewPosition = _this.position;
  82188. });
  82189. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  82190. scene._forcedViewPosition = null;
  82191. scene.updateTransformMatrix(true);
  82192. });
  82193. if (scene.activeCamera) {
  82194. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82195. }
  82196. }
  82197. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  82198. get: function () {
  82199. return this._renderTargetTexture.samples;
  82200. },
  82201. set: function (value) {
  82202. this._renderTargetTexture.samples = value;
  82203. },
  82204. enumerable: true,
  82205. configurable: true
  82206. });
  82207. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  82208. get: function () {
  82209. return this._renderTargetTexture.refreshRate;
  82210. },
  82211. set: function (value) {
  82212. this._renderTargetTexture.refreshRate = value;
  82213. },
  82214. enumerable: true,
  82215. configurable: true
  82216. });
  82217. ReflectionProbe.prototype.getScene = function () {
  82218. return this._scene;
  82219. };
  82220. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  82221. get: function () {
  82222. return this._renderTargetTexture;
  82223. },
  82224. enumerable: true,
  82225. configurable: true
  82226. });
  82227. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  82228. get: function () {
  82229. return this._renderTargetTexture.renderList;
  82230. },
  82231. enumerable: true,
  82232. configurable: true
  82233. });
  82234. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  82235. this._attachedMesh = mesh;
  82236. };
  82237. /**
  82238. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  82239. *
  82240. * @param renderingGroupId The rendering group id corresponding to its index
  82241. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  82242. */
  82243. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  82244. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  82245. };
  82246. ReflectionProbe.prototype.dispose = function () {
  82247. var index = this._scene.reflectionProbes.indexOf(this);
  82248. if (index !== -1) {
  82249. // Remove from the scene if found
  82250. this._scene.reflectionProbes.splice(index, 1);
  82251. }
  82252. if (this._renderTargetTexture) {
  82253. this._renderTargetTexture.dispose();
  82254. this._renderTargetTexture = null;
  82255. }
  82256. };
  82257. return ReflectionProbe;
  82258. }());
  82259. BABYLON.ReflectionProbe = ReflectionProbe;
  82260. })(BABYLON || (BABYLON = {}));
  82261. //# sourceMappingURL=babylon.reflectionProbe.js.map
  82262. var BABYLON;
  82263. (function (BABYLON) {
  82264. var Layer = /** @class */ (function () {
  82265. function Layer(name, imgUrl, scene, isBackground, color) {
  82266. this.name = name;
  82267. this.scale = new BABYLON.Vector2(1, 1);
  82268. this.offset = new BABYLON.Vector2(0, 0);
  82269. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  82270. this.layerMask = 0x0FFFFFFF;
  82271. this._vertexBuffers = {};
  82272. // Events
  82273. /**
  82274. * An event triggered when the layer is disposed.
  82275. * @type {BABYLON.Observable}
  82276. */
  82277. this.onDisposeObservable = new BABYLON.Observable();
  82278. /**
  82279. * An event triggered before rendering the scene
  82280. * @type {BABYLON.Observable}
  82281. */
  82282. this.onBeforeRenderObservable = new BABYLON.Observable();
  82283. /**
  82284. * An event triggered after rendering the scene
  82285. * @type {BABYLON.Observable}
  82286. */
  82287. this.onAfterRenderObservable = new BABYLON.Observable();
  82288. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  82289. this.isBackground = isBackground === undefined ? true : isBackground;
  82290. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  82291. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  82292. this._scene.layers.push(this);
  82293. var engine = this._scene.getEngine();
  82294. // VBO
  82295. var vertices = [];
  82296. vertices.push(1, 1);
  82297. vertices.push(-1, 1);
  82298. vertices.push(-1, -1);
  82299. vertices.push(1, -1);
  82300. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82301. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82302. this._createIndexBuffer();
  82303. // Effects
  82304. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  82305. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  82306. }
  82307. Object.defineProperty(Layer.prototype, "onDispose", {
  82308. set: function (callback) {
  82309. if (this._onDisposeObserver) {
  82310. this.onDisposeObservable.remove(this._onDisposeObserver);
  82311. }
  82312. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  82313. },
  82314. enumerable: true,
  82315. configurable: true
  82316. });
  82317. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  82318. set: function (callback) {
  82319. if (this._onBeforeRenderObserver) {
  82320. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  82321. }
  82322. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  82323. },
  82324. enumerable: true,
  82325. configurable: true
  82326. });
  82327. Object.defineProperty(Layer.prototype, "onAfterRender", {
  82328. set: function (callback) {
  82329. if (this._onAfterRenderObserver) {
  82330. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82331. }
  82332. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  82333. },
  82334. enumerable: true,
  82335. configurable: true
  82336. });
  82337. Layer.prototype._createIndexBuffer = function () {
  82338. var engine = this._scene.getEngine();
  82339. // Indices
  82340. var indices = [];
  82341. indices.push(0);
  82342. indices.push(1);
  82343. indices.push(2);
  82344. indices.push(0);
  82345. indices.push(2);
  82346. indices.push(3);
  82347. this._indexBuffer = engine.createIndexBuffer(indices);
  82348. };
  82349. Layer.prototype._rebuild = function () {
  82350. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82351. if (vb) {
  82352. vb._rebuild();
  82353. }
  82354. this._createIndexBuffer();
  82355. };
  82356. Layer.prototype.render = function () {
  82357. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  82358. // Check
  82359. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  82360. return;
  82361. var engine = this._scene.getEngine();
  82362. this.onBeforeRenderObservable.notifyObservers(this);
  82363. // Render
  82364. engine.enableEffect(currentEffect);
  82365. engine.setState(false);
  82366. // Texture
  82367. currentEffect.setTexture("textureSampler", this.texture);
  82368. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  82369. // Color
  82370. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  82371. // Scale / offset
  82372. currentEffect.setVector2("offset", this.offset);
  82373. currentEffect.setVector2("scale", this.scale);
  82374. // VBOs
  82375. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82376. // Draw order
  82377. if (!this.alphaTest) {
  82378. engine.setAlphaMode(this.alphaBlendingMode);
  82379. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82380. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82381. }
  82382. else {
  82383. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82384. }
  82385. this.onAfterRenderObservable.notifyObservers(this);
  82386. };
  82387. Layer.prototype.dispose = function () {
  82388. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82389. if (vertexBuffer) {
  82390. vertexBuffer.dispose();
  82391. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82392. }
  82393. if (this._indexBuffer) {
  82394. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82395. this._indexBuffer = null;
  82396. }
  82397. if (this.texture) {
  82398. this.texture.dispose();
  82399. this.texture = null;
  82400. }
  82401. // Remove from scene
  82402. var index = this._scene.layers.indexOf(this);
  82403. this._scene.layers.splice(index, 1);
  82404. // Callback
  82405. this.onDisposeObservable.notifyObservers(this);
  82406. this.onDisposeObservable.clear();
  82407. this.onAfterRenderObservable.clear();
  82408. this.onBeforeRenderObservable.clear();
  82409. };
  82410. return Layer;
  82411. }());
  82412. BABYLON.Layer = Layer;
  82413. })(BABYLON || (BABYLON = {}));
  82414. //# sourceMappingURL=babylon.layer.js.map
  82415. var BABYLON;
  82416. (function (BABYLON) {
  82417. var TextureTools = /** @class */ (function () {
  82418. function TextureTools() {
  82419. }
  82420. /**
  82421. * Uses the GPU to create a copy texture rescaled at a given size
  82422. * @param texture Texture to copy from
  82423. * @param width Desired width
  82424. * @param height Desired height
  82425. * @return Generated texture
  82426. */
  82427. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  82428. if (useBilinearMode === void 0) { useBilinearMode = true; }
  82429. var scene = texture.getScene();
  82430. var engine = scene.getEngine();
  82431. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  82432. rtt.wrapU = texture.wrapU;
  82433. rtt.wrapV = texture.wrapV;
  82434. rtt.uOffset = texture.uOffset;
  82435. rtt.vOffset = texture.vOffset;
  82436. rtt.uScale = texture.uScale;
  82437. rtt.vScale = texture.vScale;
  82438. rtt.uAng = texture.uAng;
  82439. rtt.vAng = texture.vAng;
  82440. rtt.wAng = texture.wAng;
  82441. rtt.coordinatesIndex = texture.coordinatesIndex;
  82442. rtt.level = texture.level;
  82443. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  82444. rtt._texture.isReady = false;
  82445. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82446. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82447. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82448. passPostProcess.getEffect().executeWhenCompiled(function () {
  82449. passPostProcess.onApply = function (effect) {
  82450. effect.setTexture("textureSampler", texture);
  82451. };
  82452. var internalTexture = rtt.getInternalTexture();
  82453. if (internalTexture) {
  82454. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  82455. engine.unBindFramebuffer(internalTexture);
  82456. rtt.disposeFramebufferObjects();
  82457. passPostProcess.dispose();
  82458. internalTexture.isReady = true;
  82459. }
  82460. });
  82461. return rtt;
  82462. };
  82463. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  82464. if (!scene._environmentBRDFTexture) {
  82465. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82466. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82467. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82468. scene._environmentBRDFTexture = texture;
  82469. }
  82470. return scene._environmentBRDFTexture;
  82471. };
  82472. 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=";
  82473. return TextureTools;
  82474. }());
  82475. BABYLON.TextureTools = TextureTools;
  82476. })(BABYLON || (BABYLON = {}));
  82477. //# sourceMappingURL=babylon.textureTools.js.map
  82478. var BABYLON;
  82479. (function (BABYLON) {
  82480. var FramingBehavior = /** @class */ (function () {
  82481. function FramingBehavior() {
  82482. this._mode = FramingBehavior.FitFrustumSidesMode;
  82483. this._radiusScale = 1.0;
  82484. this._positionScale = 0.5;
  82485. this._defaultElevation = 0.3;
  82486. this._elevationReturnTime = 1500;
  82487. this._elevationReturnWaitTime = 1000;
  82488. this._zoomStopsAnimation = false;
  82489. this._framingTime = 1500;
  82490. this._isPointerDown = false;
  82491. this._lastInteractionTime = -Infinity;
  82492. // Framing control
  82493. this._animatables = new Array();
  82494. this._betaIsAnimating = false;
  82495. }
  82496. Object.defineProperty(FramingBehavior.prototype, "name", {
  82497. get: function () {
  82498. return "Framing";
  82499. },
  82500. enumerable: true,
  82501. configurable: true
  82502. });
  82503. Object.defineProperty(FramingBehavior.prototype, "mode", {
  82504. /**
  82505. * Gets current mode used by the behavior.
  82506. */
  82507. get: function () {
  82508. return this._mode;
  82509. },
  82510. /**
  82511. * Sets the current mode used by the behavior
  82512. */
  82513. set: function (mode) {
  82514. this._mode = mode;
  82515. },
  82516. enumerable: true,
  82517. configurable: true
  82518. });
  82519. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  82520. /**
  82521. * Gets the scale applied to the radius
  82522. */
  82523. get: function () {
  82524. return this._radiusScale;
  82525. },
  82526. /**
  82527. * Sets the scale applied to the radius (1 by default)
  82528. */
  82529. set: function (radius) {
  82530. this._radiusScale = radius;
  82531. },
  82532. enumerable: true,
  82533. configurable: true
  82534. });
  82535. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  82536. /**
  82537. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82538. */
  82539. get: function () {
  82540. return this._positionScale;
  82541. },
  82542. /**
  82543. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82544. */
  82545. set: function (scale) {
  82546. this._positionScale = scale;
  82547. },
  82548. enumerable: true,
  82549. configurable: true
  82550. });
  82551. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  82552. /**
  82553. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82554. * behaviour is triggered, in radians.
  82555. */
  82556. get: function () {
  82557. return this._defaultElevation;
  82558. },
  82559. /**
  82560. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82561. * behaviour is triggered, in radians.
  82562. */
  82563. set: function (elevation) {
  82564. this._defaultElevation = elevation;
  82565. },
  82566. enumerable: true,
  82567. configurable: true
  82568. });
  82569. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  82570. /**
  82571. * Gets the time (in milliseconds) taken to return to the default beta position.
  82572. * Negative value indicates camera should not return to default.
  82573. */
  82574. get: function () {
  82575. return this._elevationReturnTime;
  82576. },
  82577. /**
  82578. * Sets the time (in milliseconds) taken to return to the default beta position.
  82579. * Negative value indicates camera should not return to default.
  82580. */
  82581. set: function (speed) {
  82582. this._elevationReturnTime = speed;
  82583. },
  82584. enumerable: true,
  82585. configurable: true
  82586. });
  82587. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  82588. /**
  82589. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82590. */
  82591. get: function () {
  82592. return this._elevationReturnWaitTime;
  82593. },
  82594. /**
  82595. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82596. */
  82597. set: function (time) {
  82598. this._elevationReturnWaitTime = time;
  82599. },
  82600. enumerable: true,
  82601. configurable: true
  82602. });
  82603. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  82604. /**
  82605. * Gets the flag that indicates if user zooming should stop animation.
  82606. */
  82607. get: function () {
  82608. return this._zoomStopsAnimation;
  82609. },
  82610. /**
  82611. * Sets the flag that indicates if user zooming should stop animation.
  82612. */
  82613. set: function (flag) {
  82614. this._zoomStopsAnimation = flag;
  82615. },
  82616. enumerable: true,
  82617. configurable: true
  82618. });
  82619. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  82620. /**
  82621. * Gets the transition time when framing the mesh, in milliseconds
  82622. */
  82623. get: function () {
  82624. return this._framingTime;
  82625. },
  82626. /**
  82627. * Sets the transition time when framing the mesh, in milliseconds
  82628. */
  82629. set: function (time) {
  82630. this._framingTime = time;
  82631. },
  82632. enumerable: true,
  82633. configurable: true
  82634. });
  82635. FramingBehavior.prototype.init = function () {
  82636. // Do notihng
  82637. };
  82638. FramingBehavior.prototype.attach = function (camera) {
  82639. var _this = this;
  82640. this._attachedCamera = camera;
  82641. var scene = this._attachedCamera.getScene();
  82642. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  82643. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82644. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82645. _this._isPointerDown = true;
  82646. return;
  82647. }
  82648. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82649. _this._isPointerDown = false;
  82650. }
  82651. });
  82652. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82653. if (mesh) {
  82654. _this.zoomOnMesh(mesh);
  82655. }
  82656. });
  82657. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82658. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82659. _this._applyUserInteraction();
  82660. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  82661. // back to the default position after a given timeout
  82662. _this._maintainCameraAboveGround();
  82663. });
  82664. };
  82665. FramingBehavior.prototype.detach = function () {
  82666. if (!this._attachedCamera) {
  82667. return;
  82668. }
  82669. var scene = this._attachedCamera.getScene();
  82670. if (this._onPrePointerObservableObserver) {
  82671. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82672. }
  82673. if (this._onAfterCheckInputsObserver) {
  82674. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82675. }
  82676. if (this._onMeshTargetChangedObserver) {
  82677. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82678. }
  82679. this._attachedCamera = null;
  82680. };
  82681. /**
  82682. * Targets the given mesh and updates zoom level accordingly.
  82683. * @param mesh The mesh to target.
  82684. * @param radius Optional. If a cached radius position already exists, overrides default.
  82685. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82686. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82687. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82688. */
  82689. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82690. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82691. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82692. mesh.computeWorldMatrix(true);
  82693. var boundingBox = mesh.getBoundingInfo().boundingBox;
  82694. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  82695. };
  82696. /**
  82697. * Targets the given mesh with its children and updates zoom level accordingly.
  82698. * @param mesh The mesh to target.
  82699. * @param radius Optional. If a cached radius position already exists, overrides default.
  82700. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82701. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82702. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82703. */
  82704. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82705. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82706. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82707. mesh.computeWorldMatrix(true);
  82708. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  82709. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  82710. };
  82711. /**
  82712. * Targets the given meshes with their children and updates zoom level accordingly.
  82713. * @param meshes The mesh to target.
  82714. * @param radius Optional. If a cached radius position already exists, overrides default.
  82715. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82716. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82717. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82718. */
  82719. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  82720. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82721. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82722. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  82723. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82724. for (var i = 0; i < meshes.length; i++) {
  82725. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  82726. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  82727. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  82728. }
  82729. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  82730. };
  82731. /**
  82732. * Targets the given mesh and updates zoom level accordingly.
  82733. * @param mesh The mesh to target.
  82734. * @param radius Optional. If a cached radius position already exists, overrides default.
  82735. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82736. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82737. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82738. */
  82739. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  82740. var _this = this;
  82741. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82742. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82743. var zoomTarget;
  82744. if (!this._attachedCamera) {
  82745. return;
  82746. }
  82747. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  82748. var bottom = minimumWorld.y;
  82749. var top = maximumWorld.y;
  82750. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  82751. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  82752. if (focusOnOriginXZ) {
  82753. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  82754. }
  82755. else {
  82756. var centerWorld = minimumWorld.add(radiusWorld);
  82757. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  82758. }
  82759. if (!this._vectorTransition) {
  82760. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  82761. }
  82762. this._betaIsAnimating = true;
  82763. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  82764. if (animatable) {
  82765. this._animatables.push(animatable);
  82766. }
  82767. // sets the radius and lower radius bounds
  82768. // Small delta ensures camera is not always at lower zoom limit.
  82769. var radius = 0;
  82770. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  82771. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82772. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  82773. radius = position;
  82774. }
  82775. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82776. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82777. if (this._attachedCamera.lowerRadiusLimit === null) {
  82778. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  82779. }
  82780. }
  82781. // Set sensibilities
  82782. var extend = maximumWorld.subtract(minimumWorld).length();
  82783. this._attachedCamera.panningSensibility = 5000 / extend;
  82784. this._attachedCamera.wheelPrecision = 100 / radius;
  82785. // transition to new radius
  82786. if (!this._radiusTransition) {
  82787. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82788. }
  82789. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  82790. if (onAnimationEnd) {
  82791. onAnimationEnd();
  82792. }
  82793. if (_this._attachedCamera) {
  82794. _this._attachedCamera.storeState();
  82795. }
  82796. });
  82797. if (animatable) {
  82798. this._animatables.push(animatable);
  82799. }
  82800. };
  82801. /**
  82802. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  82803. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  82804. * frustum width.
  82805. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  82806. * to fully enclose the mesh in the viewing frustum.
  82807. */
  82808. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  82809. var size = maximumWorld.subtract(minimumWorld);
  82810. var boxVectorGlobalDiagonal = size.length();
  82811. var frustumSlope = this._getFrustumSlope();
  82812. // Formula for setting distance
  82813. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  82814. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  82815. // Horizon distance
  82816. var radius = radiusWithoutFraming * this._radiusScale;
  82817. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  82818. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  82819. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  82820. var camera = this._attachedCamera;
  82821. if (!camera) {
  82822. return 0;
  82823. }
  82824. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82825. // Don't exceed the requested limit
  82826. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  82827. }
  82828. // Don't exceed the upper radius limit
  82829. if (camera.upperRadiusLimit) {
  82830. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  82831. }
  82832. return distance;
  82833. };
  82834. /**
  82835. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  82836. * is automatically returned to its default position (expected to be above ground plane).
  82837. */
  82838. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  82839. var _this = this;
  82840. if (this._elevationReturnTime < 0) {
  82841. return;
  82842. }
  82843. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  82844. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  82845. var limitBeta = Math.PI * 0.5;
  82846. // Bring the camera back up if below the ground plane
  82847. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  82848. this._betaIsAnimating = true;
  82849. //Transition to new position
  82850. this.stopAllAnimations();
  82851. if (!this._betaTransition) {
  82852. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82853. }
  82854. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  82855. _this._clearAnimationLocks();
  82856. _this.stopAllAnimations();
  82857. });
  82858. if (animatabe) {
  82859. this._animatables.push(animatabe);
  82860. }
  82861. }
  82862. };
  82863. /**
  82864. * Returns the frustum slope based on the canvas ratio and camera FOV
  82865. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  82866. */
  82867. FramingBehavior.prototype._getFrustumSlope = function () {
  82868. // Calculate the viewport ratio
  82869. // Aspect Ratio is Height/Width.
  82870. var camera = this._attachedCamera;
  82871. if (!camera) {
  82872. return BABYLON.Vector2.Zero();
  82873. }
  82874. var engine = camera.getScene().getEngine();
  82875. var aspectRatio = engine.getAspectRatio(camera);
  82876. // Camera FOV is the vertical field of view (top-bottom) in radians.
  82877. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  82878. var frustumSlopeY = Math.tan(camera.fov / 2);
  82879. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  82880. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  82881. // along the forward vector.
  82882. var frustumSlopeX = frustumSlopeY * aspectRatio;
  82883. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  82884. };
  82885. /**
  82886. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  82887. */
  82888. FramingBehavior.prototype._clearAnimationLocks = function () {
  82889. this._betaIsAnimating = false;
  82890. };
  82891. /**
  82892. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82893. */
  82894. FramingBehavior.prototype._applyUserInteraction = function () {
  82895. if (this.isUserIsMoving) {
  82896. this._lastInteractionTime = BABYLON.Tools.Now;
  82897. this.stopAllAnimations();
  82898. this._clearAnimationLocks();
  82899. }
  82900. };
  82901. /**
  82902. * Stops and removes all animations that have been applied to the camera
  82903. */
  82904. FramingBehavior.prototype.stopAllAnimations = function () {
  82905. if (this._attachedCamera) {
  82906. this._attachedCamera.animations = [];
  82907. }
  82908. while (this._animatables.length) {
  82909. if (this._animatables[0]) {
  82910. this._animatables[0].onAnimationEnd = null;
  82911. this._animatables[0].stop();
  82912. }
  82913. this._animatables.shift();
  82914. }
  82915. };
  82916. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  82917. /**
  82918. * Gets a value indicating if the user is moving the camera
  82919. */
  82920. get: function () {
  82921. if (!this._attachedCamera) {
  82922. return false;
  82923. }
  82924. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82925. this._attachedCamera.inertialBetaOffset !== 0 ||
  82926. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82927. this._attachedCamera.inertialPanningX !== 0 ||
  82928. this._attachedCamera.inertialPanningY !== 0 ||
  82929. this._isPointerDown;
  82930. },
  82931. enumerable: true,
  82932. configurable: true
  82933. });
  82934. /**
  82935. * The easing function used by animations
  82936. */
  82937. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  82938. /**
  82939. * The easing mode used by animations
  82940. */
  82941. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  82942. // Statics
  82943. /**
  82944. * The camera can move all the way towards the mesh.
  82945. */
  82946. FramingBehavior.IgnoreBoundsSizeMode = 0;
  82947. /**
  82948. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  82949. */
  82950. FramingBehavior.FitFrustumSidesMode = 1;
  82951. return FramingBehavior;
  82952. }());
  82953. BABYLON.FramingBehavior = FramingBehavior;
  82954. })(BABYLON || (BABYLON = {}));
  82955. //# sourceMappingURL=babylon.framingBehavior.js.map
  82956. var BABYLON;
  82957. (function (BABYLON) {
  82958. /**
  82959. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  82960. */
  82961. var BouncingBehavior = /** @class */ (function () {
  82962. function BouncingBehavior() {
  82963. /**
  82964. * The duration of the animation, in milliseconds
  82965. */
  82966. this.transitionDuration = 450;
  82967. /**
  82968. * Length of the distance animated by the transition when lower radius is reached
  82969. */
  82970. this.lowerRadiusTransitionRange = 2;
  82971. /**
  82972. * Length of the distance animated by the transition when upper radius is reached
  82973. */
  82974. this.upperRadiusTransitionRange = -2;
  82975. this._autoTransitionRange = false;
  82976. // Animations
  82977. this._radiusIsAnimating = false;
  82978. this._radiusBounceTransition = null;
  82979. this._animatables = new Array();
  82980. }
  82981. Object.defineProperty(BouncingBehavior.prototype, "name", {
  82982. get: function () {
  82983. return "Bouncing";
  82984. },
  82985. enumerable: true,
  82986. configurable: true
  82987. });
  82988. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  82989. /**
  82990. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82991. */
  82992. get: function () {
  82993. return this._autoTransitionRange;
  82994. },
  82995. /**
  82996. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82997. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  82998. */
  82999. set: function (value) {
  83000. var _this = this;
  83001. if (this._autoTransitionRange === value) {
  83002. return;
  83003. }
  83004. this._autoTransitionRange = value;
  83005. var camera = this._attachedCamera;
  83006. if (!camera) {
  83007. return;
  83008. }
  83009. if (value) {
  83010. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  83011. if (!mesh) {
  83012. return;
  83013. }
  83014. mesh.computeWorldMatrix(true);
  83015. var diagonal = mesh.getBoundingInfo().diagonalLength;
  83016. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  83017. _this.upperRadiusTransitionRange = diagonal * 0.05;
  83018. });
  83019. }
  83020. else if (this._onMeshTargetChangedObserver) {
  83021. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83022. }
  83023. },
  83024. enumerable: true,
  83025. configurable: true
  83026. });
  83027. BouncingBehavior.prototype.init = function () {
  83028. // Do notihng
  83029. };
  83030. BouncingBehavior.prototype.attach = function (camera) {
  83031. var _this = this;
  83032. this._attachedCamera = camera;
  83033. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83034. if (!_this._attachedCamera) {
  83035. return;
  83036. }
  83037. // Add the bounce animation to the lower radius limit
  83038. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  83039. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  83040. }
  83041. // Add the bounce animation to the upper radius limit
  83042. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  83043. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  83044. }
  83045. });
  83046. };
  83047. BouncingBehavior.prototype.detach = function () {
  83048. if (!this._attachedCamera) {
  83049. return;
  83050. }
  83051. if (this._onAfterCheckInputsObserver) {
  83052. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83053. }
  83054. if (this._onMeshTargetChangedObserver) {
  83055. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83056. }
  83057. this._attachedCamera = null;
  83058. };
  83059. /**
  83060. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  83061. * @param radiusLimit The limit to check against.
  83062. * @return Bool to indicate if at limit.
  83063. */
  83064. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  83065. if (!this._attachedCamera) {
  83066. return false;
  83067. }
  83068. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  83069. return true;
  83070. }
  83071. return false;
  83072. };
  83073. /**
  83074. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  83075. * @param radiusDelta The delta by which to animate to. Can be negative.
  83076. */
  83077. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  83078. var _this = this;
  83079. if (!this._attachedCamera) {
  83080. return;
  83081. }
  83082. if (!this._radiusBounceTransition) {
  83083. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  83084. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  83085. }
  83086. // Prevent zoom until bounce has completed
  83087. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  83088. this._attachedCamera.wheelPrecision = Infinity;
  83089. this._attachedCamera.inertialRadiusOffset = 0;
  83090. // Animate to the radius limit
  83091. this.stopAllAnimations();
  83092. this._radiusIsAnimating = true;
  83093. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  83094. if (animatable) {
  83095. this._animatables.push(animatable);
  83096. }
  83097. };
  83098. /**
  83099. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  83100. */
  83101. BouncingBehavior.prototype._clearAnimationLocks = function () {
  83102. this._radiusIsAnimating = false;
  83103. if (this._attachedCamera) {
  83104. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  83105. }
  83106. };
  83107. /**
  83108. * Stops and removes all animations that have been applied to the camera
  83109. */
  83110. BouncingBehavior.prototype.stopAllAnimations = function () {
  83111. if (this._attachedCamera) {
  83112. this._attachedCamera.animations = [];
  83113. }
  83114. while (this._animatables.length) {
  83115. this._animatables[0].onAnimationEnd = null;
  83116. this._animatables[0].stop();
  83117. this._animatables.shift();
  83118. }
  83119. };
  83120. /**
  83121. * The easing function used by animations
  83122. */
  83123. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  83124. /**
  83125. * The easing mode used by animations
  83126. */
  83127. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  83128. return BouncingBehavior;
  83129. }());
  83130. BABYLON.BouncingBehavior = BouncingBehavior;
  83131. })(BABYLON || (BABYLON = {}));
  83132. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  83133. var BABYLON;
  83134. (function (BABYLON) {
  83135. var AutoRotationBehavior = /** @class */ (function () {
  83136. function AutoRotationBehavior() {
  83137. this._zoomStopsAnimation = false;
  83138. this._idleRotationSpeed = 0.05;
  83139. this._idleRotationWaitTime = 2000;
  83140. this._idleRotationSpinupTime = 2000;
  83141. this._isPointerDown = false;
  83142. this._lastFrameTime = null;
  83143. this._lastInteractionTime = -Infinity;
  83144. this._cameraRotationSpeed = 0;
  83145. this._lastFrameRadius = 0;
  83146. }
  83147. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  83148. get: function () {
  83149. return "AutoRotation";
  83150. },
  83151. enumerable: true,
  83152. configurable: true
  83153. });
  83154. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  83155. /**
  83156. * Gets the flag that indicates if user zooming should stop animation.
  83157. */
  83158. get: function () {
  83159. return this._zoomStopsAnimation;
  83160. },
  83161. /**
  83162. * Sets the flag that indicates if user zooming should stop animation.
  83163. */
  83164. set: function (flag) {
  83165. this._zoomStopsAnimation = flag;
  83166. },
  83167. enumerable: true,
  83168. configurable: true
  83169. });
  83170. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  83171. /**
  83172. * Gets the default speed at which the camera rotates around the model.
  83173. */
  83174. get: function () {
  83175. return this._idleRotationSpeed;
  83176. },
  83177. /**
  83178. * Sets the default speed at which the camera rotates around the model.
  83179. */
  83180. set: function (speed) {
  83181. this._idleRotationSpeed = speed;
  83182. },
  83183. enumerable: true,
  83184. configurable: true
  83185. });
  83186. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  83187. /**
  83188. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  83189. */
  83190. get: function () {
  83191. return this._idleRotationWaitTime;
  83192. },
  83193. /**
  83194. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  83195. */
  83196. set: function (time) {
  83197. this._idleRotationWaitTime = time;
  83198. },
  83199. enumerable: true,
  83200. configurable: true
  83201. });
  83202. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  83203. /**
  83204. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83205. */
  83206. get: function () {
  83207. return this._idleRotationSpinupTime;
  83208. },
  83209. /**
  83210. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83211. */
  83212. set: function (time) {
  83213. this._idleRotationSpinupTime = time;
  83214. },
  83215. enumerable: true,
  83216. configurable: true
  83217. });
  83218. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  83219. /**
  83220. * Gets a value indicating if the camera is currently rotating because of this behavior
  83221. */
  83222. get: function () {
  83223. return Math.abs(this._cameraRotationSpeed) > 0;
  83224. },
  83225. enumerable: true,
  83226. configurable: true
  83227. });
  83228. AutoRotationBehavior.prototype.init = function () {
  83229. // Do notihng
  83230. };
  83231. AutoRotationBehavior.prototype.attach = function (camera) {
  83232. var _this = this;
  83233. this._attachedCamera = camera;
  83234. var scene = this._attachedCamera.getScene();
  83235. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  83236. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  83237. _this._isPointerDown = true;
  83238. return;
  83239. }
  83240. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  83241. _this._isPointerDown = false;
  83242. }
  83243. });
  83244. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83245. var now = BABYLON.Tools.Now;
  83246. var dt = 0;
  83247. if (_this._lastFrameTime != null) {
  83248. dt = now - _this._lastFrameTime;
  83249. }
  83250. _this._lastFrameTime = now;
  83251. // Stop the animation if there is user interaction and the animation should stop for this interaction
  83252. _this._applyUserInteraction();
  83253. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  83254. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  83255. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  83256. // Step camera rotation by rotation speed
  83257. if (_this._attachedCamera) {
  83258. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  83259. }
  83260. });
  83261. };
  83262. AutoRotationBehavior.prototype.detach = function () {
  83263. if (!this._attachedCamera) {
  83264. return;
  83265. }
  83266. var scene = this._attachedCamera.getScene();
  83267. if (this._onPrePointerObservableObserver) {
  83268. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  83269. }
  83270. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83271. this._attachedCamera = null;
  83272. };
  83273. /**
  83274. * Returns true if user is scrolling.
  83275. * @return true if user is scrolling.
  83276. */
  83277. AutoRotationBehavior.prototype._userIsZooming = function () {
  83278. if (!this._attachedCamera) {
  83279. return false;
  83280. }
  83281. return this._attachedCamera.inertialRadiusOffset !== 0;
  83282. };
  83283. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  83284. if (!this._attachedCamera) {
  83285. return false;
  83286. }
  83287. var zoomHasHitLimit = false;
  83288. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  83289. zoomHasHitLimit = true;
  83290. }
  83291. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  83292. this._lastFrameRadius = this._attachedCamera.radius;
  83293. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  83294. };
  83295. /**
  83296. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  83297. */
  83298. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  83299. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  83300. this._lastInteractionTime = BABYLON.Tools.Now;
  83301. }
  83302. };
  83303. // Tools
  83304. AutoRotationBehavior.prototype._userIsMoving = function () {
  83305. if (!this._attachedCamera) {
  83306. return false;
  83307. }
  83308. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  83309. this._attachedCamera.inertialBetaOffset !== 0 ||
  83310. this._attachedCamera.inertialRadiusOffset !== 0 ||
  83311. this._attachedCamera.inertialPanningX !== 0 ||
  83312. this._attachedCamera.inertialPanningY !== 0 ||
  83313. this._isPointerDown;
  83314. };
  83315. return AutoRotationBehavior;
  83316. }());
  83317. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  83318. })(BABYLON || (BABYLON = {}));
  83319. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  83320. var BABYLON;
  83321. (function (BABYLON) {
  83322. /**
  83323. * This class can be used to get instrumentation data from a Babylon engine
  83324. */
  83325. var EngineInstrumentation = /** @class */ (function () {
  83326. function EngineInstrumentation(engine) {
  83327. this.engine = engine;
  83328. this._captureGPUFrameTime = false;
  83329. this._gpuFrameTime = new BABYLON.PerfCounter();
  83330. this._captureShaderCompilationTime = false;
  83331. this._shaderCompilationTime = new BABYLON.PerfCounter();
  83332. // Observers
  83333. this._onBeginFrameObserver = null;
  83334. this._onEndFrameObserver = null;
  83335. this._onBeforeShaderCompilationObserver = null;
  83336. this._onAfterShaderCompilationObserver = null;
  83337. }
  83338. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  83339. // Properties
  83340. /**
  83341. * Gets the perf counter used for GPU frame time
  83342. */
  83343. get: function () {
  83344. return this._gpuFrameTime;
  83345. },
  83346. enumerable: true,
  83347. configurable: true
  83348. });
  83349. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  83350. /**
  83351. * Gets the GPU frame time capture status
  83352. */
  83353. get: function () {
  83354. return this._captureGPUFrameTime;
  83355. },
  83356. /**
  83357. * Enable or disable the GPU frame time capture
  83358. */
  83359. set: function (value) {
  83360. var _this = this;
  83361. if (value === this._captureGPUFrameTime) {
  83362. return;
  83363. }
  83364. this._captureGPUFrameTime = value;
  83365. if (value) {
  83366. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  83367. if (!_this._gpuFrameTimeToken) {
  83368. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  83369. }
  83370. });
  83371. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  83372. if (!_this._gpuFrameTimeToken) {
  83373. return;
  83374. }
  83375. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  83376. if (time > -1) {
  83377. _this._gpuFrameTimeToken = null;
  83378. _this._gpuFrameTime.fetchNewFrame();
  83379. _this._gpuFrameTime.addCount(time, true);
  83380. }
  83381. });
  83382. }
  83383. else {
  83384. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83385. this._onBeginFrameObserver = null;
  83386. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83387. this._onEndFrameObserver = null;
  83388. }
  83389. },
  83390. enumerable: true,
  83391. configurable: true
  83392. });
  83393. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  83394. /**
  83395. * Gets the perf counter used for shader compilation time
  83396. */
  83397. get: function () {
  83398. return this._shaderCompilationTime;
  83399. },
  83400. enumerable: true,
  83401. configurable: true
  83402. });
  83403. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  83404. /**
  83405. * Gets the shader compilation time capture status
  83406. */
  83407. get: function () {
  83408. return this._captureShaderCompilationTime;
  83409. },
  83410. /**
  83411. * Enable or disable the shader compilation time capture
  83412. */
  83413. set: function (value) {
  83414. var _this = this;
  83415. if (value === this._captureShaderCompilationTime) {
  83416. return;
  83417. }
  83418. this._captureShaderCompilationTime = value;
  83419. if (value) {
  83420. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  83421. _this._shaderCompilationTime.fetchNewFrame();
  83422. _this._shaderCompilationTime.beginMonitoring();
  83423. });
  83424. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  83425. _this._shaderCompilationTime.endMonitoring();
  83426. });
  83427. }
  83428. else {
  83429. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83430. this._onBeforeShaderCompilationObserver = null;
  83431. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83432. this._onAfterShaderCompilationObserver = null;
  83433. }
  83434. },
  83435. enumerable: true,
  83436. configurable: true
  83437. });
  83438. EngineInstrumentation.prototype.dispose = function () {
  83439. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83440. this._onBeginFrameObserver = null;
  83441. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83442. this._onEndFrameObserver = null;
  83443. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83444. this._onBeforeShaderCompilationObserver = null;
  83445. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83446. this._onAfterShaderCompilationObserver = null;
  83447. this.engine = null;
  83448. };
  83449. return EngineInstrumentation;
  83450. }());
  83451. BABYLON.EngineInstrumentation = EngineInstrumentation;
  83452. })(BABYLON || (BABYLON = {}));
  83453. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  83454. var BABYLON;
  83455. (function (BABYLON) {
  83456. /**
  83457. * This class can be used to get instrumentation data from a Babylon engine
  83458. */
  83459. var SceneInstrumentation = /** @class */ (function () {
  83460. function SceneInstrumentation(scene) {
  83461. var _this = this;
  83462. this.scene = scene;
  83463. this._captureActiveMeshesEvaluationTime = false;
  83464. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  83465. this._captureRenderTargetsRenderTime = false;
  83466. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  83467. this._captureFrameTime = false;
  83468. this._frameTime = new BABYLON.PerfCounter();
  83469. this._captureRenderTime = false;
  83470. this._renderTime = new BABYLON.PerfCounter();
  83471. this._captureInterFrameTime = false;
  83472. this._interFrameTime = new BABYLON.PerfCounter();
  83473. this._captureParticlesRenderTime = false;
  83474. this._particlesRenderTime = new BABYLON.PerfCounter();
  83475. this._captureSpritesRenderTime = false;
  83476. this._spritesRenderTime = new BABYLON.PerfCounter();
  83477. this._capturePhysicsTime = false;
  83478. this._physicsTime = new BABYLON.PerfCounter();
  83479. this._captureAnimationsTime = false;
  83480. this._animationsTime = new BABYLON.PerfCounter();
  83481. // Observers
  83482. this._onBeforeActiveMeshesEvaluationObserver = null;
  83483. this._onAfterActiveMeshesEvaluationObserver = null;
  83484. this._onBeforeRenderTargetsRenderObserver = null;
  83485. this._onAfterRenderTargetsRenderObserver = null;
  83486. this._onAfterRenderObserver = null;
  83487. this._onBeforeDrawPhaseObserver = null;
  83488. this._onAfterDrawPhaseObserver = null;
  83489. this._onBeforeAnimationsObserver = null;
  83490. this._onBeforeParticlesRenderingObserver = null;
  83491. this._onAfterParticlesRenderingObserver = null;
  83492. this._onBeforeSpritesRenderingObserver = null;
  83493. this._onAfterSpritesRenderingObserver = null;
  83494. this._onBeforePhysicsObserver = null;
  83495. this._onAfterPhysicsObserver = null;
  83496. this._onAfterAnimationsObserver = null;
  83497. // Before render
  83498. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  83499. if (_this._captureActiveMeshesEvaluationTime) {
  83500. _this._activeMeshesEvaluationTime.fetchNewFrame();
  83501. }
  83502. if (_this._captureRenderTargetsRenderTime) {
  83503. _this._renderTargetsRenderTime.fetchNewFrame();
  83504. }
  83505. if (_this._captureFrameTime) {
  83506. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  83507. _this._frameTime.beginMonitoring();
  83508. }
  83509. if (_this._captureInterFrameTime) {
  83510. _this._interFrameTime.endMonitoring();
  83511. }
  83512. if (_this._captureParticlesRenderTime) {
  83513. _this._particlesRenderTime.fetchNewFrame();
  83514. }
  83515. if (_this._captureSpritesRenderTime) {
  83516. _this._spritesRenderTime.fetchNewFrame();
  83517. }
  83518. if (_this._captureAnimationsTime) {
  83519. _this._animationsTime.beginMonitoring();
  83520. }
  83521. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  83522. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  83523. });
  83524. // After render
  83525. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  83526. if (_this._captureFrameTime) {
  83527. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  83528. _this._frameTime.endMonitoring();
  83529. }
  83530. if (_this._captureRenderTime) {
  83531. _this._renderTime.endMonitoring(false);
  83532. }
  83533. if (_this._captureInterFrameTime) {
  83534. _this._interFrameTime.beginMonitoring();
  83535. }
  83536. });
  83537. }
  83538. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  83539. // Properties
  83540. /**
  83541. * Gets the perf counter used for active meshes evaluation time
  83542. */
  83543. get: function () {
  83544. return this._activeMeshesEvaluationTime;
  83545. },
  83546. enumerable: true,
  83547. configurable: true
  83548. });
  83549. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  83550. /**
  83551. * Gets the active meshes evaluation time capture status
  83552. */
  83553. get: function () {
  83554. return this._captureActiveMeshesEvaluationTime;
  83555. },
  83556. /**
  83557. * Enable or disable the active meshes evaluation time capture
  83558. */
  83559. set: function (value) {
  83560. var _this = this;
  83561. if (value === this._captureActiveMeshesEvaluationTime) {
  83562. return;
  83563. }
  83564. this._captureActiveMeshesEvaluationTime = value;
  83565. if (value) {
  83566. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  83567. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  83568. _this._activeMeshesEvaluationTime.beginMonitoring();
  83569. });
  83570. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  83571. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  83572. _this._activeMeshesEvaluationTime.endMonitoring();
  83573. });
  83574. }
  83575. else {
  83576. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83577. this._onBeforeActiveMeshesEvaluationObserver = null;
  83578. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83579. this._onAfterActiveMeshesEvaluationObserver = null;
  83580. }
  83581. },
  83582. enumerable: true,
  83583. configurable: true
  83584. });
  83585. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  83586. /**
  83587. * Gets the perf counter used for render targets render time
  83588. */
  83589. get: function () {
  83590. return this._renderTargetsRenderTime;
  83591. },
  83592. enumerable: true,
  83593. configurable: true
  83594. });
  83595. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  83596. /**
  83597. * Gets the render targets render time capture status
  83598. */
  83599. get: function () {
  83600. return this._captureRenderTargetsRenderTime;
  83601. },
  83602. /**
  83603. * Enable or disable the render targets render time capture
  83604. */
  83605. set: function (value) {
  83606. var _this = this;
  83607. if (value === this._captureRenderTargetsRenderTime) {
  83608. return;
  83609. }
  83610. this._captureRenderTargetsRenderTime = value;
  83611. if (value) {
  83612. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  83613. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  83614. _this._renderTargetsRenderTime.beginMonitoring();
  83615. });
  83616. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  83617. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  83618. _this._renderTargetsRenderTime.endMonitoring(false);
  83619. });
  83620. }
  83621. else {
  83622. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83623. this._onBeforeRenderTargetsRenderObserver = null;
  83624. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83625. this._onAfterRenderTargetsRenderObserver = null;
  83626. }
  83627. },
  83628. enumerable: true,
  83629. configurable: true
  83630. });
  83631. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  83632. /**
  83633. * Gets the perf counter used for particles render time
  83634. */
  83635. get: function () {
  83636. return this._particlesRenderTime;
  83637. },
  83638. enumerable: true,
  83639. configurable: true
  83640. });
  83641. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  83642. /**
  83643. * Gets the particles render time capture status
  83644. */
  83645. get: function () {
  83646. return this._captureParticlesRenderTime;
  83647. },
  83648. /**
  83649. * Enable or disable the particles render time capture
  83650. */
  83651. set: function (value) {
  83652. var _this = this;
  83653. if (value === this._captureParticlesRenderTime) {
  83654. return;
  83655. }
  83656. this._captureParticlesRenderTime = value;
  83657. if (value) {
  83658. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  83659. BABYLON.Tools.StartPerformanceCounter("Particles");
  83660. _this._particlesRenderTime.beginMonitoring();
  83661. });
  83662. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  83663. BABYLON.Tools.EndPerformanceCounter("Particles");
  83664. _this._particlesRenderTime.endMonitoring(false);
  83665. });
  83666. }
  83667. else {
  83668. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83669. this._onBeforeParticlesRenderingObserver = null;
  83670. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83671. this._onAfterParticlesRenderingObserver = null;
  83672. }
  83673. },
  83674. enumerable: true,
  83675. configurable: true
  83676. });
  83677. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  83678. /**
  83679. * Gets the perf counter used for sprites render time
  83680. */
  83681. get: function () {
  83682. return this._spritesRenderTime;
  83683. },
  83684. enumerable: true,
  83685. configurable: true
  83686. });
  83687. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  83688. /**
  83689. * Gets the sprites render time capture status
  83690. */
  83691. get: function () {
  83692. return this._captureSpritesRenderTime;
  83693. },
  83694. /**
  83695. * Enable or disable the sprites render time capture
  83696. */
  83697. set: function (value) {
  83698. var _this = this;
  83699. if (value === this._captureSpritesRenderTime) {
  83700. return;
  83701. }
  83702. this._captureSpritesRenderTime = value;
  83703. if (value) {
  83704. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  83705. BABYLON.Tools.StartPerformanceCounter("Sprites");
  83706. _this._spritesRenderTime.beginMonitoring();
  83707. });
  83708. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  83709. BABYLON.Tools.EndPerformanceCounter("Sprites");
  83710. _this._spritesRenderTime.endMonitoring(false);
  83711. });
  83712. }
  83713. else {
  83714. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83715. this._onBeforeSpritesRenderingObserver = null;
  83716. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83717. this._onAfterSpritesRenderingObserver = null;
  83718. }
  83719. },
  83720. enumerable: true,
  83721. configurable: true
  83722. });
  83723. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  83724. /**
  83725. * Gets the perf counter used for physics time
  83726. */
  83727. get: function () {
  83728. return this._physicsTime;
  83729. },
  83730. enumerable: true,
  83731. configurable: true
  83732. });
  83733. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  83734. /**
  83735. * Gets the physics time capture status
  83736. */
  83737. get: function () {
  83738. return this._capturePhysicsTime;
  83739. },
  83740. /**
  83741. * Enable or disable the physics time capture
  83742. */
  83743. set: function (value) {
  83744. var _this = this;
  83745. if (value === this._capturePhysicsTime) {
  83746. return;
  83747. }
  83748. this._capturePhysicsTime = value;
  83749. if (value) {
  83750. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  83751. BABYLON.Tools.StartPerformanceCounter("Physics");
  83752. _this._physicsTime.beginMonitoring();
  83753. });
  83754. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  83755. BABYLON.Tools.EndPerformanceCounter("Physics");
  83756. _this._physicsTime.endMonitoring();
  83757. });
  83758. }
  83759. else {
  83760. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83761. this._onBeforePhysicsObserver = null;
  83762. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83763. this._onAfterPhysicsObserver = null;
  83764. }
  83765. },
  83766. enumerable: true,
  83767. configurable: true
  83768. });
  83769. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  83770. /**
  83771. * Gets the perf counter used for animations time
  83772. */
  83773. get: function () {
  83774. return this._animationsTime;
  83775. },
  83776. enumerable: true,
  83777. configurable: true
  83778. });
  83779. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  83780. /**
  83781. * Gets the animations time capture status
  83782. */
  83783. get: function () {
  83784. return this._captureAnimationsTime;
  83785. },
  83786. /**
  83787. * Enable or disable the animations time capture
  83788. */
  83789. set: function (value) {
  83790. var _this = this;
  83791. if (value === this._captureAnimationsTime) {
  83792. return;
  83793. }
  83794. this._captureAnimationsTime = value;
  83795. if (value) {
  83796. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  83797. _this._animationsTime.endMonitoring();
  83798. });
  83799. }
  83800. else {
  83801. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83802. this._onAfterAnimationsObserver = null;
  83803. }
  83804. },
  83805. enumerable: true,
  83806. configurable: true
  83807. });
  83808. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  83809. /**
  83810. * Gets the perf counter used for frame time capture
  83811. */
  83812. get: function () {
  83813. return this._frameTime;
  83814. },
  83815. enumerable: true,
  83816. configurable: true
  83817. });
  83818. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  83819. /**
  83820. * Gets the frame time capture status
  83821. */
  83822. get: function () {
  83823. return this._captureFrameTime;
  83824. },
  83825. /**
  83826. * Enable or disable the frame time capture
  83827. */
  83828. set: function (value) {
  83829. this._captureFrameTime = value;
  83830. },
  83831. enumerable: true,
  83832. configurable: true
  83833. });
  83834. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  83835. /**
  83836. * Gets the perf counter used for inter-frames time capture
  83837. */
  83838. get: function () {
  83839. return this._interFrameTime;
  83840. },
  83841. enumerable: true,
  83842. configurable: true
  83843. });
  83844. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  83845. /**
  83846. * Gets the inter-frames time capture status
  83847. */
  83848. get: function () {
  83849. return this._captureInterFrameTime;
  83850. },
  83851. /**
  83852. * Enable or disable the inter-frames time capture
  83853. */
  83854. set: function (value) {
  83855. this._captureInterFrameTime = value;
  83856. },
  83857. enumerable: true,
  83858. configurable: true
  83859. });
  83860. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  83861. /**
  83862. * Gets the perf counter used for render time capture
  83863. */
  83864. get: function () {
  83865. return this._renderTime;
  83866. },
  83867. enumerable: true,
  83868. configurable: true
  83869. });
  83870. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  83871. /**
  83872. * Gets the render time capture status
  83873. */
  83874. get: function () {
  83875. return this._captureRenderTime;
  83876. },
  83877. /**
  83878. * Enable or disable the render time capture
  83879. */
  83880. set: function (value) {
  83881. var _this = this;
  83882. if (value === this._captureRenderTime) {
  83883. return;
  83884. }
  83885. this._captureRenderTime = value;
  83886. if (value) {
  83887. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  83888. _this._renderTime.beginMonitoring();
  83889. BABYLON.Tools.StartPerformanceCounter("Main render");
  83890. });
  83891. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  83892. _this._renderTime.endMonitoring(false);
  83893. BABYLON.Tools.EndPerformanceCounter("Main render");
  83894. });
  83895. }
  83896. else {
  83897. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83898. this._onBeforeDrawPhaseObserver = null;
  83899. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83900. this._onAfterDrawPhaseObserver = null;
  83901. }
  83902. },
  83903. enumerable: true,
  83904. configurable: true
  83905. });
  83906. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  83907. /**
  83908. * Gets the perf counter used for draw calls
  83909. */
  83910. get: function () {
  83911. return this.scene.getEngine()._drawCalls;
  83912. },
  83913. enumerable: true,
  83914. configurable: true
  83915. });
  83916. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  83917. /**
  83918. * Gets the perf counter used for texture collisions
  83919. */
  83920. get: function () {
  83921. return this.scene.getEngine()._textureCollisions;
  83922. },
  83923. enumerable: true,
  83924. configurable: true
  83925. });
  83926. SceneInstrumentation.prototype.dispose = function () {
  83927. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83928. this._onAfterRenderObserver = null;
  83929. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83930. this._onBeforeActiveMeshesEvaluationObserver = null;
  83931. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83932. this._onAfterActiveMeshesEvaluationObserver = null;
  83933. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83934. this._onBeforeRenderTargetsRenderObserver = null;
  83935. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83936. this._onAfterRenderTargetsRenderObserver = null;
  83937. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  83938. this._onBeforeAnimationsObserver = null;
  83939. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83940. this._onBeforeParticlesRenderingObserver = null;
  83941. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83942. this._onAfterParticlesRenderingObserver = null;
  83943. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83944. this._onBeforeSpritesRenderingObserver = null;
  83945. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83946. this._onAfterSpritesRenderingObserver = null;
  83947. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83948. this._onBeforeDrawPhaseObserver = null;
  83949. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83950. this._onAfterDrawPhaseObserver = null;
  83951. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83952. this._onBeforePhysicsObserver = null;
  83953. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83954. this._onAfterPhysicsObserver = null;
  83955. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83956. this._onAfterAnimationsObserver = null;
  83957. this.scene = null;
  83958. };
  83959. return SceneInstrumentation;
  83960. }());
  83961. BABYLON.SceneInstrumentation = SceneInstrumentation;
  83962. })(BABYLON || (BABYLON = {}));
  83963. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  83964. var BABYLON;
  83965. (function (BABYLON) {
  83966. var _TimeToken = /** @class */ (function () {
  83967. function _TimeToken() {
  83968. this._timeElapsedQueryEnded = false;
  83969. }
  83970. return _TimeToken;
  83971. }());
  83972. BABYLON._TimeToken = _TimeToken;
  83973. })(BABYLON || (BABYLON = {}));
  83974. //# sourceMappingURL=babylon.timeToken.js.map
  83975. var BABYLON;
  83976. (function (BABYLON) {
  83977. /**
  83978. * Background material defines definition.
  83979. * @ignore Mainly internal Use
  83980. */
  83981. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  83982. __extends(BackgroundMaterialDefines, _super);
  83983. /**
  83984. * Constructor of the defines.
  83985. */
  83986. function BackgroundMaterialDefines() {
  83987. var _this = _super.call(this) || this;
  83988. /**
  83989. * True if the diffuse texture is in use.
  83990. */
  83991. _this.DIFFUSE = false;
  83992. /**
  83993. * The direct UV channel to use.
  83994. */
  83995. _this.DIFFUSEDIRECTUV = 0;
  83996. /**
  83997. * True if the diffuse texture is in gamma space.
  83998. */
  83999. _this.GAMMADIFFUSE = false;
  84000. /**
  84001. * True if the diffuse texture has opacity in the alpha channel.
  84002. */
  84003. _this.DIFFUSEHASALPHA = false;
  84004. /**
  84005. * True if you want the material to fade to transparent at grazing angle.
  84006. */
  84007. _this.OPACITYFRESNEL = false;
  84008. /**
  84009. * True if an extra blur needs to be added in the reflection.
  84010. */
  84011. _this.REFLECTIONBLUR = false;
  84012. /**
  84013. * True if you want the material to fade to reflection at grazing angle.
  84014. */
  84015. _this.REFLECTIONFRESNEL = false;
  84016. /**
  84017. * True if you want the material to falloff as far as you move away from the scene center.
  84018. */
  84019. _this.REFLECTIONFALLOFF = false;
  84020. /**
  84021. * False if the current Webgl implementation does not support the texture lod extension.
  84022. */
  84023. _this.TEXTURELODSUPPORT = false;
  84024. /**
  84025. * True to ensure the data are premultiplied.
  84026. */
  84027. _this.PREMULTIPLYALPHA = false;
  84028. /**
  84029. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  84030. */
  84031. _this.USERGBCOLOR = false;
  84032. /**
  84033. * True to add noise in order to reduce the banding effect.
  84034. */
  84035. _this.NOISE = false;
  84036. // Image Processing Configuration.
  84037. _this.IMAGEPROCESSING = false;
  84038. _this.VIGNETTE = false;
  84039. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84040. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84041. _this.TONEMAPPING = false;
  84042. _this.CONTRAST = false;
  84043. _this.COLORCURVES = false;
  84044. _this.COLORGRADING = false;
  84045. _this.COLORGRADING3D = false;
  84046. _this.SAMPLER3DGREENDEPTH = false;
  84047. _this.SAMPLER3DBGRMAP = false;
  84048. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84049. _this.EXPOSURE = false;
  84050. // Reflection.
  84051. _this.REFLECTION = false;
  84052. _this.REFLECTIONMAP_3D = false;
  84053. _this.REFLECTIONMAP_SPHERICAL = false;
  84054. _this.REFLECTIONMAP_PLANAR = false;
  84055. _this.REFLECTIONMAP_CUBIC = false;
  84056. _this.REFLECTIONMAP_PROJECTION = false;
  84057. _this.REFLECTIONMAP_SKYBOX = false;
  84058. _this.REFLECTIONMAP_EXPLICIT = false;
  84059. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84060. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84061. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84062. _this.INVERTCUBICMAP = false;
  84063. _this.REFLECTIONMAP_OPPOSITEZ = false;
  84064. _this.LODINREFLECTIONALPHA = false;
  84065. _this.GAMMAREFLECTION = false;
  84066. // Default BJS.
  84067. _this.MAINUV1 = false;
  84068. _this.MAINUV2 = false;
  84069. _this.UV1 = false;
  84070. _this.UV2 = false;
  84071. _this.CLIPPLANE = false;
  84072. _this.POINTSIZE = false;
  84073. _this.FOG = false;
  84074. _this.NORMAL = false;
  84075. _this.NUM_BONE_INFLUENCERS = 0;
  84076. _this.BonesPerMesh = 0;
  84077. _this.INSTANCES = false;
  84078. _this.SHADOWFLOAT = false;
  84079. _this.rebuild();
  84080. return _this;
  84081. }
  84082. return BackgroundMaterialDefines;
  84083. }(BABYLON.MaterialDefines));
  84084. /**
  84085. * Background material used to create an efficient environement around your scene.
  84086. */
  84087. var BackgroundMaterial = /** @class */ (function (_super) {
  84088. __extends(BackgroundMaterial, _super);
  84089. /**
  84090. * Instantiates a Background Material in the given scene
  84091. * @param name The friendly name of the material
  84092. * @param scene The scene to add the material to
  84093. */
  84094. function BackgroundMaterial(name, scene) {
  84095. var _this = _super.call(this, name, scene) || this;
  84096. /**
  84097. * Key light Color (multiply against the R channel of the environement texture)
  84098. */
  84099. _this.primaryColor = BABYLON.Color3.White();
  84100. /**
  84101. * Key light Level (allowing HDR output of the background)
  84102. */
  84103. _this.primaryLevel = 1;
  84104. /**
  84105. * Secondary light Color (multiply against the G channel of the environement texture)
  84106. */
  84107. _this.secondaryColor = BABYLON.Color3.Gray();
  84108. /**
  84109. * Secondary light Level (allowing HDR output of the background)
  84110. */
  84111. _this.secondaryLevel = 1;
  84112. /**
  84113. * Tertiary light Color (multiply against the B channel of the environement texture)
  84114. */
  84115. _this.tertiaryColor = BABYLON.Color3.Black();
  84116. /**
  84117. * Tertiary light Level (allowing HDR output of the background)
  84118. */
  84119. _this.tertiaryLevel = 1;
  84120. /**
  84121. * Reflection Texture used in the material.
  84122. * Should be author in a specific way for the best result (refer to the documentation).
  84123. */
  84124. _this.reflectionTexture = null;
  84125. /**
  84126. * Reflection Texture level of blur.
  84127. *
  84128. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  84129. * texture twice.
  84130. */
  84131. _this.reflectionBlur = 0;
  84132. /**
  84133. * Diffuse Texture used in the material.
  84134. * Should be author in a specific way for the best result (refer to the documentation).
  84135. */
  84136. _this.diffuseTexture = null;
  84137. _this._shadowLights = null;
  84138. /**
  84139. * Specify the list of lights casting shadow on the material.
  84140. * All scene shadow lights will be included if null.
  84141. */
  84142. _this.shadowLights = null;
  84143. /**
  84144. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  84145. * soft lighting on the background.
  84146. */
  84147. _this.shadowBlurScale = 1;
  84148. /**
  84149. * Helps adjusting the shadow to a softer level if required.
  84150. * 0 means black shadows and 1 means no shadows.
  84151. */
  84152. _this.shadowLevel = 0;
  84153. /**
  84154. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  84155. * It is usually zero but might be interesting to modify according to your setup.
  84156. */
  84157. _this.sceneCenter = BABYLON.Vector3.Zero();
  84158. /**
  84159. * This helps specifying that the material is falling off to the sky box at grazing angle.
  84160. * This helps ensuring a nice transition when the camera goes under the ground.
  84161. */
  84162. _this.opacityFresnel = true;
  84163. /**
  84164. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  84165. * This helps adding a mirror texture on the ground.
  84166. */
  84167. _this.reflectionFresnel = false;
  84168. /**
  84169. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  84170. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  84171. */
  84172. _this.reflectionFalloffDistance = 0.0;
  84173. /**
  84174. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  84175. */
  84176. _this.reflectionAmount = 1.0;
  84177. /**
  84178. * This specifies the weight of the reflection at grazing angle.
  84179. */
  84180. _this.reflectionReflectance0 = 0.05;
  84181. /**
  84182. * This specifies the weight of the reflection at a perpendicular point of view.
  84183. */
  84184. _this.reflectionReflectance90 = 0.5;
  84185. /**
  84186. * Helps to directly use the maps channels instead of their level.
  84187. */
  84188. _this.useRGBColor = true;
  84189. /**
  84190. * This helps reducing the banding effect that could occur on the background.
  84191. */
  84192. _this.enableNoise = false;
  84193. _this._maxSimultaneousLights = 4;
  84194. /**
  84195. * Number of Simultaneous lights allowed on the material.
  84196. */
  84197. _this.maxSimultaneousLights = 4;
  84198. /**
  84199. * Keep track of the image processing observer to allow dispose and replace.
  84200. */
  84201. _this._imageProcessingObserver = null;
  84202. // Temp values kept as cache in the material.
  84203. _this._renderTargets = new BABYLON.SmartArray(16);
  84204. _this._reflectionControls = BABYLON.Vector4.Zero();
  84205. // Setup the default processing configuration to the scene.
  84206. _this._attachImageProcessingConfiguration(null);
  84207. _this.getRenderTargetTextures = function () {
  84208. _this._renderTargets.reset();
  84209. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  84210. _this._renderTargets.push(_this._diffuseTexture);
  84211. }
  84212. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  84213. _this._renderTargets.push(_this._reflectionTexture);
  84214. }
  84215. return _this._renderTargets;
  84216. };
  84217. return _this;
  84218. }
  84219. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  84220. /**
  84221. * Sets the reflection reflectance fresnel values according to the default standard
  84222. * empirically know to work well :-)
  84223. */
  84224. set: function (value) {
  84225. var reflectionWeight = value;
  84226. if (reflectionWeight < 0.5) {
  84227. reflectionWeight = reflectionWeight * 2.0;
  84228. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  84229. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  84230. }
  84231. else {
  84232. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  84233. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  84234. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  84235. }
  84236. },
  84237. enumerable: true,
  84238. configurable: true
  84239. });
  84240. /**
  84241. * Attaches a new image processing configuration to the PBR Material.
  84242. * @param configuration (if null the scene configuration will be use)
  84243. */
  84244. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  84245. var _this = this;
  84246. if (configuration === this._imageProcessingConfiguration) {
  84247. return;
  84248. }
  84249. // Detaches observer.
  84250. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84251. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84252. }
  84253. // Pick the scene configuration if needed.
  84254. if (!configuration) {
  84255. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  84256. }
  84257. else {
  84258. this._imageProcessingConfiguration = configuration;
  84259. }
  84260. // Attaches observer.
  84261. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84262. _this._markAllSubMeshesAsImageProcessingDirty();
  84263. });
  84264. };
  84265. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  84266. /**
  84267. * Gets the image processing configuration used either in this material.
  84268. */
  84269. get: function () {
  84270. return this._imageProcessingConfiguration;
  84271. },
  84272. /**
  84273. * Sets the Default image processing configuration used either in the this material.
  84274. *
  84275. * If sets to null, the scene one is in use.
  84276. */
  84277. set: function (value) {
  84278. this._attachImageProcessingConfiguration(value);
  84279. // Ensure the effect will be rebuilt.
  84280. this._markAllSubMeshesAsTexturesDirty();
  84281. },
  84282. enumerable: true,
  84283. configurable: true
  84284. });
  84285. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  84286. /**
  84287. * Gets wether the color curves effect is enabled.
  84288. */
  84289. get: function () {
  84290. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84291. },
  84292. /**
  84293. * Sets wether the color curves effect is enabled.
  84294. */
  84295. set: function (value) {
  84296. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84297. },
  84298. enumerable: true,
  84299. configurable: true
  84300. });
  84301. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  84302. /**
  84303. * Gets wether the color grading effect is enabled.
  84304. */
  84305. get: function () {
  84306. return this.imageProcessingConfiguration.colorGradingEnabled;
  84307. },
  84308. /**
  84309. * Gets wether the color grading effect is enabled.
  84310. */
  84311. set: function (value) {
  84312. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84313. },
  84314. enumerable: true,
  84315. configurable: true
  84316. });
  84317. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  84318. /**
  84319. * Gets wether tonemapping is enabled or not.
  84320. */
  84321. get: function () {
  84322. return this._imageProcessingConfiguration.toneMappingEnabled;
  84323. },
  84324. /**
  84325. * Sets wether tonemapping is enabled or not
  84326. */
  84327. set: function (value) {
  84328. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84329. },
  84330. enumerable: true,
  84331. configurable: true
  84332. });
  84333. ;
  84334. ;
  84335. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  84336. /**
  84337. * The camera exposure used on this material.
  84338. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84339. * This corresponds to a photographic exposure.
  84340. */
  84341. get: function () {
  84342. return this._imageProcessingConfiguration.exposure;
  84343. },
  84344. /**
  84345. * The camera exposure used on this material.
  84346. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84347. * This corresponds to a photographic exposure.
  84348. */
  84349. set: function (value) {
  84350. this._imageProcessingConfiguration.exposure = value;
  84351. },
  84352. enumerable: true,
  84353. configurable: true
  84354. });
  84355. ;
  84356. ;
  84357. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  84358. /**
  84359. * Gets The camera contrast used on this material.
  84360. */
  84361. get: function () {
  84362. return this._imageProcessingConfiguration.contrast;
  84363. },
  84364. /**
  84365. * Sets The camera contrast used on this material.
  84366. */
  84367. set: function (value) {
  84368. this._imageProcessingConfiguration.contrast = value;
  84369. },
  84370. enumerable: true,
  84371. configurable: true
  84372. });
  84373. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  84374. /**
  84375. * Gets the Color Grading 2D Lookup Texture.
  84376. */
  84377. get: function () {
  84378. return this._imageProcessingConfiguration.colorGradingTexture;
  84379. },
  84380. /**
  84381. * Sets the Color Grading 2D Lookup Texture.
  84382. */
  84383. set: function (value) {
  84384. this.imageProcessingConfiguration.colorGradingTexture = value;
  84385. },
  84386. enumerable: true,
  84387. configurable: true
  84388. });
  84389. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  84390. /**
  84391. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84392. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84393. * 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;
  84394. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84395. */
  84396. get: function () {
  84397. return this.imageProcessingConfiguration.colorCurves;
  84398. },
  84399. /**
  84400. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84401. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84402. * 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;
  84403. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84404. */
  84405. set: function (value) {
  84406. this.imageProcessingConfiguration.colorCurves = value;
  84407. },
  84408. enumerable: true,
  84409. configurable: true
  84410. });
  84411. /**
  84412. * The entire material has been created in order to prevent overdraw.
  84413. * @returns false
  84414. */
  84415. BackgroundMaterial.prototype.needAlphaTesting = function () {
  84416. return true;
  84417. };
  84418. /**
  84419. * The entire material has been created in order to prevent overdraw.
  84420. * @returns true if blending is enable
  84421. */
  84422. BackgroundMaterial.prototype.needAlphaBlending = function () {
  84423. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  84424. };
  84425. /**
  84426. * Checks wether the material is ready to be rendered for a given mesh.
  84427. * @param mesh The mesh to render
  84428. * @param subMesh The submesh to check against
  84429. * @param useInstances Specify wether or not the material is used with instances
  84430. * @returns true if all the dependencies are ready (Textures, Effects...)
  84431. */
  84432. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  84433. var _this = this;
  84434. if (useInstances === void 0) { useInstances = false; }
  84435. if (subMesh.effect && this.isFrozen) {
  84436. if (this._wasPreviouslyReady) {
  84437. return true;
  84438. }
  84439. }
  84440. if (!subMesh._materialDefines) {
  84441. subMesh._materialDefines = new BackgroundMaterialDefines();
  84442. }
  84443. var scene = this.getScene();
  84444. var defines = subMesh._materialDefines;
  84445. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  84446. if (defines._renderId === scene.getRenderId()) {
  84447. return true;
  84448. }
  84449. }
  84450. var engine = scene.getEngine();
  84451. // Lights
  84452. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  84453. defines._needNormals = true;
  84454. // Textures
  84455. if (defines._areTexturesDirty) {
  84456. defines._needUVs = false;
  84457. if (scene.texturesEnabled) {
  84458. if (scene.getEngine().getCaps().textureLOD) {
  84459. defines.TEXTURELODSUPPORT = true;
  84460. }
  84461. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84462. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  84463. return false;
  84464. }
  84465. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  84466. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  84467. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  84468. defines.OPACITYFRESNEL = this._opacityFresnel;
  84469. }
  84470. else {
  84471. defines.DIFFUSE = false;
  84472. defines.DIFFUSEHASALPHA = false;
  84473. defines.GAMMADIFFUSE = false;
  84474. defines.OPACITYFRESNEL = false;
  84475. }
  84476. var reflectionTexture = this._reflectionTexture;
  84477. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84478. if (!reflectionTexture.isReadyOrNotBlocking()) {
  84479. return false;
  84480. }
  84481. defines.REFLECTION = true;
  84482. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  84483. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  84484. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  84485. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  84486. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  84487. defines.INVERTCUBICMAP = true;
  84488. }
  84489. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  84490. switch (reflectionTexture.coordinatesMode) {
  84491. case BABYLON.Texture.CUBIC_MODE:
  84492. case BABYLON.Texture.INVCUBIC_MODE:
  84493. defines.REFLECTIONMAP_CUBIC = true;
  84494. break;
  84495. case BABYLON.Texture.EXPLICIT_MODE:
  84496. defines.REFLECTIONMAP_EXPLICIT = true;
  84497. break;
  84498. case BABYLON.Texture.PLANAR_MODE:
  84499. defines.REFLECTIONMAP_PLANAR = true;
  84500. break;
  84501. case BABYLON.Texture.PROJECTION_MODE:
  84502. defines.REFLECTIONMAP_PROJECTION = true;
  84503. break;
  84504. case BABYLON.Texture.SKYBOX_MODE:
  84505. defines.REFLECTIONMAP_SKYBOX = true;
  84506. break;
  84507. case BABYLON.Texture.SPHERICAL_MODE:
  84508. defines.REFLECTIONMAP_SPHERICAL = true;
  84509. break;
  84510. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  84511. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  84512. break;
  84513. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  84514. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  84515. break;
  84516. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  84517. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  84518. break;
  84519. }
  84520. if (this.reflectionFresnel) {
  84521. defines.REFLECTIONFRESNEL = true;
  84522. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  84523. this._reflectionControls.x = this.reflectionAmount;
  84524. this._reflectionControls.y = this.reflectionReflectance0;
  84525. this._reflectionControls.z = this.reflectionReflectance90;
  84526. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  84527. }
  84528. else {
  84529. defines.REFLECTIONFRESNEL = false;
  84530. defines.REFLECTIONFALLOFF = false;
  84531. }
  84532. }
  84533. else {
  84534. defines.REFLECTION = false;
  84535. defines.REFLECTIONFALLOFF = false;
  84536. defines.REFLECTIONBLUR = false;
  84537. defines.REFLECTIONMAP_3D = false;
  84538. defines.REFLECTIONMAP_SPHERICAL = false;
  84539. defines.REFLECTIONMAP_PLANAR = false;
  84540. defines.REFLECTIONMAP_CUBIC = false;
  84541. defines.REFLECTIONMAP_PROJECTION = false;
  84542. defines.REFLECTIONMAP_SKYBOX = false;
  84543. defines.REFLECTIONMAP_EXPLICIT = false;
  84544. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84545. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84546. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84547. defines.INVERTCUBICMAP = false;
  84548. defines.REFLECTIONMAP_OPPOSITEZ = false;
  84549. defines.LODINREFLECTIONALPHA = false;
  84550. defines.GAMMAREFLECTION = false;
  84551. }
  84552. }
  84553. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  84554. defines.USERGBCOLOR = this._useRGBColor;
  84555. defines.NOISE = this._enableNoise;
  84556. }
  84557. if (defines._areImageProcessingDirty) {
  84558. if (!this._imageProcessingConfiguration.isReady()) {
  84559. return false;
  84560. }
  84561. this._imageProcessingConfiguration.prepareDefines(defines);
  84562. }
  84563. // Misc.
  84564. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  84565. // Values that need to be evaluated on every frame
  84566. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  84567. // Attribs
  84568. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  84569. if (mesh) {
  84570. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84571. mesh.createNormals(true);
  84572. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  84573. }
  84574. }
  84575. }
  84576. // Get correct effect
  84577. if (defines.isDirty) {
  84578. defines.markAsProcessed();
  84579. scene.resetCachedMaterial();
  84580. // Fallbacks
  84581. var fallbacks = new BABYLON.EffectFallbacks();
  84582. if (defines.FOG) {
  84583. fallbacks.addFallback(0, "FOG");
  84584. }
  84585. if (defines.POINTSIZE) {
  84586. fallbacks.addFallback(1, "POINTSIZE");
  84587. }
  84588. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  84589. if (defines.NUM_BONE_INFLUENCERS > 0) {
  84590. fallbacks.addCPUSkinningFallback(0, mesh);
  84591. }
  84592. //Attributes
  84593. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84594. if (defines.NORMAL) {
  84595. attribs.push(BABYLON.VertexBuffer.NormalKind);
  84596. }
  84597. if (defines.UV1) {
  84598. attribs.push(BABYLON.VertexBuffer.UVKind);
  84599. }
  84600. if (defines.UV2) {
  84601. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84602. }
  84603. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  84604. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  84605. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  84606. "vFogInfos", "vFogColor", "pointSize",
  84607. "vClipPlane", "mBones",
  84608. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  84609. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  84610. "shadowLevel", "alpha",
  84611. "vBackgroundCenter", "vReflectionControl",
  84612. "vDiffuseInfos", "diffuseMatrix",
  84613. ];
  84614. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  84615. var uniformBuffers = ["Material", "Scene"];
  84616. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  84617. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  84618. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  84619. uniformsNames: uniforms,
  84620. uniformBuffersNames: uniformBuffers,
  84621. samplers: samplers,
  84622. defines: defines,
  84623. maxSimultaneousLights: this._maxSimultaneousLights
  84624. });
  84625. var onCompiled = function (effect) {
  84626. if (_this.onCompiled) {
  84627. _this.onCompiled(effect);
  84628. }
  84629. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  84630. };
  84631. var join = defines.toString();
  84632. subMesh.setEffect(scene.getEngine().createEffect("background", {
  84633. attributes: attribs,
  84634. uniformsNames: uniforms,
  84635. uniformBuffersNames: uniformBuffers,
  84636. samplers: samplers,
  84637. defines: join,
  84638. fallbacks: fallbacks,
  84639. onCompiled: onCompiled,
  84640. onError: this.onError,
  84641. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  84642. }, engine), defines);
  84643. this.buildUniformLayout();
  84644. }
  84645. if (!subMesh.effect || !subMesh.effect.isReady()) {
  84646. return false;
  84647. }
  84648. defines._renderId = scene.getRenderId();
  84649. this._wasPreviouslyReady = true;
  84650. return true;
  84651. };
  84652. /**
  84653. * Build the uniform buffer used in the material.
  84654. */
  84655. BackgroundMaterial.prototype.buildUniformLayout = function () {
  84656. // Order is important !
  84657. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  84658. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  84659. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  84660. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  84661. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  84662. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  84663. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  84664. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  84665. this._uniformBuffer.addUniform("pointSize", 1);
  84666. this._uniformBuffer.addUniform("shadowLevel", 1);
  84667. this._uniformBuffer.addUniform("alpha", 1);
  84668. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  84669. this._uniformBuffer.addUniform("vReflectionControl", 4);
  84670. this._uniformBuffer.create();
  84671. };
  84672. /**
  84673. * Unbind the material.
  84674. */
  84675. BackgroundMaterial.prototype.unbind = function () {
  84676. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  84677. this._uniformBuffer.setTexture("diffuseSampler", null);
  84678. }
  84679. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  84680. this._uniformBuffer.setTexture("reflectionSampler", null);
  84681. }
  84682. _super.prototype.unbind.call(this);
  84683. };
  84684. /**
  84685. * Bind only the world matrix to the material.
  84686. * @param world The world matrix to bind.
  84687. */
  84688. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  84689. this._activeEffect.setMatrix("world", world);
  84690. };
  84691. /**
  84692. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  84693. * @param world The world matrix to bind.
  84694. * @param subMesh The submesh to bind for.
  84695. */
  84696. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  84697. var scene = this.getScene();
  84698. var defines = subMesh._materialDefines;
  84699. if (!defines) {
  84700. return;
  84701. }
  84702. var effect = subMesh.effect;
  84703. if (!effect) {
  84704. return;
  84705. }
  84706. this._activeEffect = effect;
  84707. // Matrices
  84708. this.bindOnlyWorldMatrix(world);
  84709. // Bones
  84710. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  84711. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  84712. if (mustRebind) {
  84713. this._uniformBuffer.bindToEffect(effect, "Material");
  84714. this.bindViewProjection(effect);
  84715. var reflectionTexture = this._reflectionTexture;
  84716. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  84717. // Texture uniforms
  84718. if (scene.texturesEnabled) {
  84719. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84720. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  84721. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  84722. }
  84723. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84724. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  84725. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  84726. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  84727. }
  84728. }
  84729. if (this.shadowLevel > 0) {
  84730. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  84731. }
  84732. this._uniformBuffer.updateFloat("alpha", this.alpha);
  84733. // Point size
  84734. if (this.pointsCloud) {
  84735. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  84736. }
  84737. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  84738. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  84739. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  84740. }
  84741. // Textures
  84742. if (scene.texturesEnabled) {
  84743. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84744. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  84745. }
  84746. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84747. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  84748. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84749. }
  84750. else if (!defines.REFLECTIONBLUR) {
  84751. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84752. }
  84753. else {
  84754. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  84755. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  84756. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  84757. }
  84758. if (defines.REFLECTIONFRESNEL) {
  84759. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  84760. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  84761. }
  84762. }
  84763. }
  84764. // Clip plane
  84765. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  84766. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  84767. }
  84768. if (mustRebind || !this.isFrozen) {
  84769. if (scene.lightsEnabled) {
  84770. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  84771. }
  84772. // View
  84773. this.bindView(effect);
  84774. // Fog
  84775. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84776. // image processing
  84777. this._imageProcessingConfiguration.bind(this._activeEffect);
  84778. }
  84779. this._uniformBuffer.update();
  84780. this._afterBind(mesh);
  84781. };
  84782. /**
  84783. * Dispose the material.
  84784. * @param forceDisposeEffect Force disposal of the associated effect.
  84785. * @param forceDisposeTextures Force disposal of the associated textures.
  84786. */
  84787. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  84788. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  84789. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  84790. if (forceDisposeTextures) {
  84791. if (this.diffuseTexture) {
  84792. this.diffuseTexture.dispose();
  84793. }
  84794. if (this.reflectionTexture) {
  84795. this.reflectionTexture.dispose();
  84796. }
  84797. }
  84798. this._renderTargets.dispose();
  84799. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84800. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84801. }
  84802. _super.prototype.dispose.call(this, forceDisposeEffect);
  84803. };
  84804. /**
  84805. * Clones the material.
  84806. * @param name The cloned name.
  84807. * @returns The cloned material.
  84808. */
  84809. BackgroundMaterial.prototype.clone = function (name) {
  84810. var _this = this;
  84811. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  84812. };
  84813. /**
  84814. * Serializes the current material to its JSON representation.
  84815. * @returns The JSON representation.
  84816. */
  84817. BackgroundMaterial.prototype.serialize = function () {
  84818. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84819. serializationObject.customType = "BABYLON.BackgroundMaterial";
  84820. return serializationObject;
  84821. };
  84822. /**
  84823. * Gets the class name of the material
  84824. * @returns "BackgroundMaterial"
  84825. */
  84826. BackgroundMaterial.prototype.getClassName = function () {
  84827. return "BackgroundMaterial";
  84828. };
  84829. /**
  84830. * Parse a JSON input to create back a background material.
  84831. * @param source The JSON data to parse
  84832. * @param scene The scene to create the parsed material in
  84833. * @param rootUrl The root url of the assets the material depends upon
  84834. * @returns the instantiated BackgroundMaterial.
  84835. */
  84836. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  84837. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  84838. };
  84839. /**
  84840. * Standard reflectance value at parallel view angle.
  84841. */
  84842. BackgroundMaterial.StandardReflectance0 = 0.05;
  84843. /**
  84844. * Standard reflectance value at grazing angle.
  84845. */
  84846. BackgroundMaterial.StandardReflectance90 = 0.5;
  84847. __decorate([
  84848. BABYLON.serializeAsColor3()
  84849. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  84850. __decorate([
  84851. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84852. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  84853. __decorate([
  84854. BABYLON.serialize()
  84855. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  84856. __decorate([
  84857. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84858. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  84859. __decorate([
  84860. BABYLON.serializeAsColor3()
  84861. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  84862. __decorate([
  84863. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84864. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  84865. __decorate([
  84866. BABYLON.serialize()
  84867. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  84868. __decorate([
  84869. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84870. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  84871. __decorate([
  84872. BABYLON.serializeAsColor3()
  84873. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  84874. __decorate([
  84875. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84876. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  84877. __decorate([
  84878. BABYLON.serialize()
  84879. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  84880. __decorate([
  84881. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84882. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  84883. __decorate([
  84884. BABYLON.serializeAsTexture()
  84885. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  84886. __decorate([
  84887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84888. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  84889. __decorate([
  84890. BABYLON.serialize()
  84891. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  84892. __decorate([
  84893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84894. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  84895. __decorate([
  84896. BABYLON.serializeAsTexture()
  84897. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  84898. __decorate([
  84899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84900. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  84901. __decorate([
  84902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84903. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  84904. __decorate([
  84905. BABYLON.serialize()
  84906. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  84907. __decorate([
  84908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84909. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  84910. __decorate([
  84911. BABYLON.serialize()
  84912. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  84913. __decorate([
  84914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84915. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  84916. __decorate([
  84917. BABYLON.serializeAsVector3()
  84918. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  84919. __decorate([
  84920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84921. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  84922. __decorate([
  84923. BABYLON.serialize()
  84924. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  84925. __decorate([
  84926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84927. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  84928. __decorate([
  84929. BABYLON.serialize()
  84930. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  84931. __decorate([
  84932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84933. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  84934. __decorate([
  84935. BABYLON.serialize()
  84936. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  84937. __decorate([
  84938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84939. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  84940. __decorate([
  84941. BABYLON.serialize()
  84942. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  84943. __decorate([
  84944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84945. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  84946. __decorate([
  84947. BABYLON.serialize()
  84948. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  84949. __decorate([
  84950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84951. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  84952. __decorate([
  84953. BABYLON.serialize()
  84954. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  84955. __decorate([
  84956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84957. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  84958. __decorate([
  84959. BABYLON.serialize()
  84960. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  84961. __decorate([
  84962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84963. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  84964. __decorate([
  84965. BABYLON.serialize()
  84966. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  84967. __decorate([
  84968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84969. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  84970. __decorate([
  84971. BABYLON.serialize()
  84972. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  84973. __decorate([
  84974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84975. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  84976. __decorate([
  84977. BABYLON.serializeAsImageProcessingConfiguration()
  84978. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  84979. return BackgroundMaterial;
  84980. }(BABYLON.PushMaterial));
  84981. BABYLON.BackgroundMaterial = BackgroundMaterial;
  84982. })(BABYLON || (BABYLON = {}));
  84983. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  84984. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84985. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84986. s = arguments[i];
  84987. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84988. t[p] = s[p];
  84989. }
  84990. return t;
  84991. };
  84992. var BABYLON;
  84993. (function (BABYLON) {
  84994. /**
  84995. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  84996. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  84997. * It also helps with the default setup of your imageProcessing configuration.
  84998. */
  84999. var EnvironmentHelper = /** @class */ (function () {
  85000. /**
  85001. * constructor
  85002. * @param options
  85003. * @param scene The scene to add the material to
  85004. */
  85005. function EnvironmentHelper(options, scene) {
  85006. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  85007. this._scene = scene;
  85008. this._setupBackground();
  85009. this._setupImageProcessing();
  85010. }
  85011. /**
  85012. * Creates the default options for the helper.
  85013. */
  85014. EnvironmentHelper._getDefaultOptions = function () {
  85015. return {
  85016. createGround: true,
  85017. groundSize: 15,
  85018. groundTexture: this._groundTextureCDNUrl,
  85019. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85020. groundOpacity: 0.9,
  85021. enableGroundShadow: true,
  85022. groundShadowLevel: 0.5,
  85023. enableGroundMirror: false,
  85024. groundMirrorSizeRatio: 0.3,
  85025. groundMirrorBlurKernel: 64,
  85026. groundMirrorAmount: 1,
  85027. groundMirrorFresnelWeight: 1,
  85028. groundMirrorFallOffDistance: 0,
  85029. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  85030. groundYBias: 0.00001,
  85031. createSkybox: true,
  85032. skyboxSize: 20,
  85033. skyboxTexture: this._skyboxTextureCDNUrl,
  85034. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85035. backgroundYRotation: 0,
  85036. sizeAuto: true,
  85037. rootPosition: BABYLON.Vector3.Zero(),
  85038. setupImageProcessing: true,
  85039. environmentTexture: this._environmentTextureCDNUrl,
  85040. cameraExposure: 0.8,
  85041. cameraContrast: 1.2,
  85042. toneMappingEnabled: true,
  85043. };
  85044. };
  85045. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  85046. /**
  85047. * Gets the root mesh created by the helper.
  85048. */
  85049. get: function () {
  85050. return this._rootMesh;
  85051. },
  85052. enumerable: true,
  85053. configurable: true
  85054. });
  85055. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  85056. /**
  85057. * Gets the skybox created by the helper.
  85058. */
  85059. get: function () {
  85060. return this._skybox;
  85061. },
  85062. enumerable: true,
  85063. configurable: true
  85064. });
  85065. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  85066. /**
  85067. * Gets the skybox texture created by the helper.
  85068. */
  85069. get: function () {
  85070. return this._skyboxTexture;
  85071. },
  85072. enumerable: true,
  85073. configurable: true
  85074. });
  85075. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  85076. /**
  85077. * Gets the skybox material created by the helper.
  85078. */
  85079. get: function () {
  85080. return this._skyboxMaterial;
  85081. },
  85082. enumerable: true,
  85083. configurable: true
  85084. });
  85085. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  85086. /**
  85087. * Gets the ground mesh created by the helper.
  85088. */
  85089. get: function () {
  85090. return this._ground;
  85091. },
  85092. enumerable: true,
  85093. configurable: true
  85094. });
  85095. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  85096. /**
  85097. * Gets the ground texture created by the helper.
  85098. */
  85099. get: function () {
  85100. return this._groundTexture;
  85101. },
  85102. enumerable: true,
  85103. configurable: true
  85104. });
  85105. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  85106. /**
  85107. * Gets the ground mirror created by the helper.
  85108. */
  85109. get: function () {
  85110. return this._groundMirror;
  85111. },
  85112. enumerable: true,
  85113. configurable: true
  85114. });
  85115. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  85116. /**
  85117. * Gets the ground mirror render list to helps pushing the meshes
  85118. * you wish in the ground reflection.
  85119. */
  85120. get: function () {
  85121. if (this._groundMirror) {
  85122. return this._groundMirror.renderList;
  85123. }
  85124. return null;
  85125. },
  85126. enumerable: true,
  85127. configurable: true
  85128. });
  85129. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  85130. /**
  85131. * Gets the ground material created by the helper.
  85132. */
  85133. get: function () {
  85134. return this._groundMaterial;
  85135. },
  85136. enumerable: true,
  85137. configurable: true
  85138. });
  85139. /**
  85140. * Updates the background according to the new options
  85141. * @param options
  85142. */
  85143. EnvironmentHelper.prototype.updateOptions = function (options) {
  85144. var newOptions = __assign({}, this._options, options);
  85145. if (this._ground && !newOptions.createGround) {
  85146. this._ground.dispose();
  85147. this._ground = null;
  85148. }
  85149. if (this._groundMaterial && !newOptions.createGround) {
  85150. this._groundMaterial.dispose();
  85151. this._groundMaterial = null;
  85152. }
  85153. if (this._groundTexture) {
  85154. if (this._options.groundTexture != newOptions.groundTexture) {
  85155. this._groundTexture.dispose();
  85156. this._groundTexture = null;
  85157. }
  85158. }
  85159. if (this._skybox && !newOptions.createSkybox) {
  85160. this._skybox.dispose();
  85161. this._skybox = null;
  85162. }
  85163. if (this._skyboxMaterial && !newOptions.createSkybox) {
  85164. this._skyboxMaterial.dispose();
  85165. this._skyboxMaterial = null;
  85166. }
  85167. if (this._skyboxTexture) {
  85168. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  85169. this._skyboxTexture.dispose();
  85170. this._skyboxTexture = null;
  85171. }
  85172. }
  85173. if (this._groundMirror && !newOptions.enableGroundMirror) {
  85174. this._groundMirror.dispose();
  85175. this._groundMirror = null;
  85176. }
  85177. if (this._scene.environmentTexture) {
  85178. if (this._options.environmentTexture != newOptions.environmentTexture) {
  85179. this._scene.environmentTexture.dispose();
  85180. }
  85181. }
  85182. this._options = newOptions;
  85183. this._setupBackground();
  85184. this._setupImageProcessing();
  85185. };
  85186. /**
  85187. * Sets the primary color of all the available elements.
  85188. * @param color
  85189. */
  85190. EnvironmentHelper.prototype.setMainColor = function (color) {
  85191. if (this.groundMaterial) {
  85192. this.groundMaterial.primaryColor = color;
  85193. }
  85194. if (this.skyboxMaterial) {
  85195. this.skyboxMaterial.primaryColor = color;
  85196. }
  85197. if (this.groundMirror) {
  85198. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  85199. }
  85200. };
  85201. /**
  85202. * Setup the image processing according to the specified options.
  85203. */
  85204. EnvironmentHelper.prototype._setupImageProcessing = function () {
  85205. if (this._options.setupImageProcessing) {
  85206. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  85207. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  85208. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  85209. this._setupEnvironmentTexture();
  85210. }
  85211. };
  85212. /**
  85213. * Setup the environment texture according to the specified options.
  85214. */
  85215. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  85216. if (this._scene.environmentTexture) {
  85217. return;
  85218. }
  85219. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  85220. this._scene.environmentTexture = this._options.environmentTexture;
  85221. return;
  85222. }
  85223. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  85224. this._scene.environmentTexture = environmentTexture;
  85225. };
  85226. /**
  85227. * Setup the background according to the specified options.
  85228. */
  85229. EnvironmentHelper.prototype._setupBackground = function () {
  85230. if (!this._rootMesh) {
  85231. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  85232. }
  85233. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  85234. var sceneSize = this._getSceneSize();
  85235. if (this._options.createGround) {
  85236. this._setupGround(sceneSize);
  85237. this._setupGroundMaterial();
  85238. this._setupGroundDiffuseTexture();
  85239. if (this._options.enableGroundMirror) {
  85240. this._setupGroundMirrorTexture(sceneSize);
  85241. }
  85242. this._setupMirrorInGroundMaterial();
  85243. }
  85244. if (this._options.createSkybox) {
  85245. this._setupSkybox(sceneSize);
  85246. this._setupSkyboxMaterial();
  85247. this._setupSkyboxReflectionTexture();
  85248. }
  85249. this._rootMesh.position.x = sceneSize.rootPosition.x;
  85250. this._rootMesh.position.z = sceneSize.rootPosition.z;
  85251. this._rootMesh.position.y = sceneSize.rootPosition.y;
  85252. };
  85253. /**
  85254. * Get the scene sizes according to the setup.
  85255. */
  85256. EnvironmentHelper.prototype._getSceneSize = function () {
  85257. var groundSize = this._options.groundSize;
  85258. var skyboxSize = this._options.skyboxSize;
  85259. var rootPosition = this._options.rootPosition;
  85260. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  85261. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85262. }
  85263. var sceneExtends = this._scene.getWorldExtends();
  85264. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  85265. if (this._options.sizeAuto) {
  85266. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  85267. this._scene.activeCamera.upperRadiusLimit) {
  85268. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  85269. skyboxSize = groundSize;
  85270. }
  85271. var sceneDiagonalLenght = sceneDiagonal.length();
  85272. if (sceneDiagonalLenght > groundSize) {
  85273. groundSize = sceneDiagonalLenght * 2;
  85274. skyboxSize = groundSize;
  85275. }
  85276. // 10 % bigger.
  85277. groundSize *= 1.1;
  85278. skyboxSize *= 1.5;
  85279. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  85280. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  85281. }
  85282. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85283. };
  85284. /**
  85285. * Setup the ground according to the specified options.
  85286. */
  85287. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  85288. var _this = this;
  85289. if (!this._ground) {
  85290. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  85291. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  85292. this._ground.parent = this._rootMesh;
  85293. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  85294. }
  85295. this._ground.receiveShadows = this._options.enableGroundShadow;
  85296. };
  85297. /**
  85298. * Setup the ground material according to the specified options.
  85299. */
  85300. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  85301. if (!this._groundMaterial) {
  85302. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  85303. }
  85304. this._groundMaterial.alpha = this._options.groundOpacity;
  85305. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  85306. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  85307. this._groundMaterial.primaryLevel = 1;
  85308. this._groundMaterial.primaryColor = this._options.groundColor;
  85309. this._groundMaterial.secondaryLevel = 0;
  85310. this._groundMaterial.tertiaryLevel = 0;
  85311. this._groundMaterial.useRGBColor = false;
  85312. this._groundMaterial.enableNoise = true;
  85313. if (this._ground) {
  85314. this._ground.material = this._groundMaterial;
  85315. }
  85316. };
  85317. /**
  85318. * Setup the ground diffuse texture according to the specified options.
  85319. */
  85320. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  85321. if (!this._groundMaterial) {
  85322. return;
  85323. }
  85324. if (this._groundTexture) {
  85325. return;
  85326. }
  85327. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  85328. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  85329. return;
  85330. }
  85331. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  85332. diffuseTexture.gammaSpace = false;
  85333. diffuseTexture.hasAlpha = true;
  85334. this._groundMaterial.diffuseTexture = diffuseTexture;
  85335. };
  85336. /**
  85337. * Setup the ground mirror texture according to the specified options.
  85338. */
  85339. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  85340. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85341. if (!this._groundMirror) {
  85342. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  85343. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  85344. this._groundMirror.anisotropicFilteringLevel = 1;
  85345. this._groundMirror.wrapU = wrapping;
  85346. this._groundMirror.wrapV = wrapping;
  85347. this._groundMirror.gammaSpace = false;
  85348. if (this._groundMirror.renderList) {
  85349. for (var i = 0; i < this._scene.meshes.length; i++) {
  85350. var mesh = this._scene.meshes[i];
  85351. if (mesh !== this._ground &&
  85352. mesh !== this._skybox &&
  85353. mesh !== this._rootMesh) {
  85354. this._groundMirror.renderList.push(mesh);
  85355. }
  85356. }
  85357. }
  85358. }
  85359. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  85360. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  85361. };
  85362. /**
  85363. * Setup the ground to receive the mirror texture.
  85364. */
  85365. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  85366. if (this._groundMaterial) {
  85367. this._groundMaterial.reflectionTexture = this._groundMirror;
  85368. this._groundMaterial.reflectionFresnel = true;
  85369. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  85370. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  85371. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  85372. }
  85373. };
  85374. /**
  85375. * Setup the skybox according to the specified options.
  85376. */
  85377. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  85378. var _this = this;
  85379. if (!this._skybox) {
  85380. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  85381. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  85382. }
  85383. this._skybox.parent = this._rootMesh;
  85384. };
  85385. /**
  85386. * Setup the skybox material according to the specified options.
  85387. */
  85388. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  85389. if (!this._skybox) {
  85390. return;
  85391. }
  85392. if (!this._skyboxMaterial) {
  85393. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  85394. }
  85395. this._skyboxMaterial.useRGBColor = false;
  85396. this._skyboxMaterial.primaryLevel = 1;
  85397. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  85398. this._skyboxMaterial.secondaryLevel = 0;
  85399. this._skyboxMaterial.tertiaryLevel = 0;
  85400. this._skyboxMaterial.enableNoise = true;
  85401. this._skybox.material = this._skyboxMaterial;
  85402. };
  85403. /**
  85404. * Setup the skybox reflection texture according to the specified options.
  85405. */
  85406. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  85407. if (!this._skyboxMaterial) {
  85408. return;
  85409. }
  85410. if (this._skyboxTexture) {
  85411. return;
  85412. }
  85413. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  85414. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85415. return;
  85416. }
  85417. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  85418. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  85419. this._skyboxTexture.gammaSpace = false;
  85420. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  85421. };
  85422. /**
  85423. * Dispose all the elements created by the Helper.
  85424. */
  85425. EnvironmentHelper.prototype.dispose = function () {
  85426. if (this._groundMaterial) {
  85427. this._groundMaterial.dispose(true, true);
  85428. }
  85429. if (this._skyboxMaterial) {
  85430. this._skyboxMaterial.dispose(true, true);
  85431. }
  85432. this._rootMesh.dispose(false);
  85433. };
  85434. /**
  85435. * Default ground texture URL.
  85436. */
  85437. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  85438. /**
  85439. * Default skybox texture URL.
  85440. */
  85441. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  85442. /**
  85443. * Default environment texture URL.
  85444. */
  85445. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  85446. return EnvironmentHelper;
  85447. }());
  85448. BABYLON.EnvironmentHelper = EnvironmentHelper;
  85449. })(BABYLON || (BABYLON = {}));
  85450. //# sourceMappingURL=babylon.environmentHelper.js.map
  85451. 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,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\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 depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\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\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\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#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\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}"};
  85452. 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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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\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#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 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;\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 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};"};
  85453. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85454. var BABYLON;
  85455. (function (BABYLON) {
  85456. var GridMaterialDefines = /** @class */ (function (_super) {
  85457. __extends(GridMaterialDefines, _super);
  85458. function GridMaterialDefines() {
  85459. var _this = _super.call(this) || this;
  85460. _this.TRANSPARENT = false;
  85461. _this.FOG = false;
  85462. _this.PREMULTIPLYALPHA = false;
  85463. _this.rebuild();
  85464. return _this;
  85465. }
  85466. return GridMaterialDefines;
  85467. }(BABYLON.MaterialDefines));
  85468. /**
  85469. * The grid materials allows you to wrap any shape with a grid.
  85470. * Colors are customizable.
  85471. */
  85472. var GridMaterial = /** @class */ (function (_super) {
  85473. __extends(GridMaterial, _super);
  85474. /**
  85475. * constructor
  85476. * @param name The name given to the material in order to identify it afterwards.
  85477. * @param scene The scene the material is used in.
  85478. */
  85479. function GridMaterial(name, scene) {
  85480. var _this = _super.call(this, name, scene) || this;
  85481. /**
  85482. * Main color of the grid (e.g. between lines)
  85483. */
  85484. _this.mainColor = BABYLON.Color3.Black();
  85485. /**
  85486. * Color of the grid lines.
  85487. */
  85488. _this.lineColor = BABYLON.Color3.Teal();
  85489. /**
  85490. * The scale of the grid compared to unit.
  85491. */
  85492. _this.gridRatio = 1.0;
  85493. /**
  85494. * Allows setting an offset for the grid lines.
  85495. */
  85496. _this.gridOffset = BABYLON.Vector3.Zero();
  85497. /**
  85498. * The frequency of thicker lines.
  85499. */
  85500. _this.majorUnitFrequency = 10;
  85501. /**
  85502. * The visibility of minor units in the grid.
  85503. */
  85504. _this.minorUnitVisibility = 0.33;
  85505. /**
  85506. * The grid opacity outside of the lines.
  85507. */
  85508. _this.opacity = 1.0;
  85509. /**
  85510. * Determine RBG output is premultiplied by alpha value.
  85511. */
  85512. _this.preMultiplyAlpha = false;
  85513. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  85514. return _this;
  85515. }
  85516. /**
  85517. * Returns wehter or not the grid requires alpha blending.
  85518. */
  85519. GridMaterial.prototype.needAlphaBlending = function () {
  85520. return this.opacity < 1.0;
  85521. };
  85522. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  85523. return this.needAlphaBlending();
  85524. };
  85525. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85526. if (this.isFrozen) {
  85527. if (this._wasPreviouslyReady && subMesh.effect) {
  85528. return true;
  85529. }
  85530. }
  85531. if (!subMesh._materialDefines) {
  85532. subMesh._materialDefines = new GridMaterialDefines();
  85533. }
  85534. var defines = subMesh._materialDefines;
  85535. var scene = this.getScene();
  85536. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85537. if (this._renderId === scene.getRenderId()) {
  85538. return true;
  85539. }
  85540. }
  85541. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  85542. defines.TRANSPARENT = !defines.TRANSPARENT;
  85543. defines.markAsUnprocessed();
  85544. }
  85545. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  85546. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  85547. defines.markAsUnprocessed();
  85548. }
  85549. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  85550. // Get correct effect
  85551. if (defines.isDirty) {
  85552. defines.markAsProcessed();
  85553. scene.resetCachedMaterial();
  85554. // Attributes
  85555. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85556. // Defines
  85557. var join = defines.toString();
  85558. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  85559. }
  85560. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85561. return false;
  85562. }
  85563. this._renderId = scene.getRenderId();
  85564. this._wasPreviouslyReady = true;
  85565. return true;
  85566. };
  85567. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85568. var scene = this.getScene();
  85569. var defines = subMesh._materialDefines;
  85570. if (!defines) {
  85571. return;
  85572. }
  85573. var effect = subMesh.effect;
  85574. if (!effect) {
  85575. return;
  85576. }
  85577. this._activeEffect = effect;
  85578. // Matrices
  85579. this.bindOnlyWorldMatrix(world);
  85580. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  85581. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  85582. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  85583. // Uniforms
  85584. if (this._mustRebind(scene, effect)) {
  85585. this._activeEffect.setColor3("mainColor", this.mainColor);
  85586. this._activeEffect.setColor3("lineColor", this.lineColor);
  85587. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  85588. this._gridControl.x = this.gridRatio;
  85589. this._gridControl.y = Math.round(this.majorUnitFrequency);
  85590. this._gridControl.z = this.minorUnitVisibility;
  85591. this._gridControl.w = this.opacity;
  85592. this._activeEffect.setVector4("gridControl", this._gridControl);
  85593. }
  85594. // Fog
  85595. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85596. this._afterBind(mesh, this._activeEffect);
  85597. };
  85598. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  85599. _super.prototype.dispose.call(this, forceDisposeEffect);
  85600. };
  85601. GridMaterial.prototype.clone = function (name) {
  85602. var _this = this;
  85603. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  85604. };
  85605. GridMaterial.prototype.serialize = function () {
  85606. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85607. serializationObject.customType = "BABYLON.GridMaterial";
  85608. return serializationObject;
  85609. };
  85610. GridMaterial.prototype.getClassName = function () {
  85611. return "GridMaterial";
  85612. };
  85613. GridMaterial.Parse = function (source, scene, rootUrl) {
  85614. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  85615. };
  85616. __decorate([
  85617. BABYLON.serializeAsColor3()
  85618. ], GridMaterial.prototype, "mainColor", void 0);
  85619. __decorate([
  85620. BABYLON.serializeAsColor3()
  85621. ], GridMaterial.prototype, "lineColor", void 0);
  85622. __decorate([
  85623. BABYLON.serialize()
  85624. ], GridMaterial.prototype, "gridRatio", void 0);
  85625. __decorate([
  85626. BABYLON.serializeAsColor3()
  85627. ], GridMaterial.prototype, "gridOffset", void 0);
  85628. __decorate([
  85629. BABYLON.serialize()
  85630. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  85631. __decorate([
  85632. BABYLON.serialize()
  85633. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  85634. __decorate([
  85635. BABYLON.serialize()
  85636. ], GridMaterial.prototype, "opacity", void 0);
  85637. __decorate([
  85638. BABYLON.serialize()
  85639. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  85640. return GridMaterial;
  85641. }(BABYLON.PushMaterial));
  85642. BABYLON.GridMaterial = GridMaterial;
  85643. })(BABYLON || (BABYLON = {}));
  85644. //# sourceMappingURL=babylon.gridmaterial.js.map
  85645. 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}";
  85646. 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}";
  85647. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85648. var BABYLON;
  85649. (function (BABYLON) {
  85650. var GLTFLoaderCoordinateSystemMode;
  85651. (function (GLTFLoaderCoordinateSystemMode) {
  85652. /**
  85653. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  85654. */
  85655. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  85656. /**
  85657. * Sets the useRightHandedSystem flag on the scene.
  85658. */
  85659. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  85660. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  85661. var GLTFLoaderAnimationStartMode;
  85662. (function (GLTFLoaderAnimationStartMode) {
  85663. /**
  85664. * No animation will start.
  85665. */
  85666. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  85667. /**
  85668. * The first animation will start.
  85669. */
  85670. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  85671. /**
  85672. * All animations will start.
  85673. */
  85674. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  85675. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  85676. var GLTFFileLoader = /** @class */ (function () {
  85677. function GLTFFileLoader() {
  85678. // #region Common options
  85679. /**
  85680. * Raised when the asset has been parsed.
  85681. * The data.json property stores the glTF JSON.
  85682. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  85683. */
  85684. this.onParsedObservable = new BABYLON.Observable();
  85685. // #endregion
  85686. // #region V2 options
  85687. /**
  85688. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  85689. */
  85690. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  85691. /**
  85692. * The animation start mode (NONE, FIRST, ALL).
  85693. */
  85694. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  85695. /**
  85696. * Set to true to compile materials before raising the success callback.
  85697. */
  85698. this.compileMaterials = false;
  85699. /**
  85700. * Set to true to also compile materials with clip planes.
  85701. */
  85702. this.useClipPlane = false;
  85703. /**
  85704. * Set to true to compile shadow generators before raising the success callback.
  85705. */
  85706. this.compileShadowGenerators = false;
  85707. /**
  85708. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  85709. */
  85710. this.onMeshLoadedObservable = new BABYLON.Observable();
  85711. /**
  85712. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  85713. */
  85714. this.onTextureLoadedObservable = new BABYLON.Observable();
  85715. /**
  85716. * Raised when the loader creates a material after parsing the glTF properties of the material.
  85717. */
  85718. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85719. /**
  85720. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  85721. * For assets with LODs, raised when all of the LODs are complete.
  85722. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  85723. */
  85724. this.onCompleteObservable = new BABYLON.Observable();
  85725. /**
  85726. * Raised when the loader is disposed.
  85727. */
  85728. this.onDisposeObservable = new BABYLON.Observable();
  85729. // #endregion
  85730. this._loader = null;
  85731. this.name = "gltf";
  85732. this.extensions = {
  85733. ".gltf": { isBinary: false },
  85734. ".glb": { isBinary: true }
  85735. };
  85736. }
  85737. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  85738. set: function (callback) {
  85739. if (this._onParsedObserver) {
  85740. this.onParsedObservable.remove(this._onParsedObserver);
  85741. }
  85742. this._onParsedObserver = this.onParsedObservable.add(callback);
  85743. },
  85744. enumerable: true,
  85745. configurable: true
  85746. });
  85747. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  85748. set: function (callback) {
  85749. if (this._onMeshLoadedObserver) {
  85750. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  85751. }
  85752. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  85753. },
  85754. enumerable: true,
  85755. configurable: true
  85756. });
  85757. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  85758. set: function (callback) {
  85759. if (this._onTextureLoadedObserver) {
  85760. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  85761. }
  85762. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  85763. },
  85764. enumerable: true,
  85765. configurable: true
  85766. });
  85767. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  85768. set: function (callback) {
  85769. if (this._onMaterialLoadedObserver) {
  85770. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  85771. }
  85772. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  85773. },
  85774. enumerable: true,
  85775. configurable: true
  85776. });
  85777. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  85778. set: function (callback) {
  85779. if (this._onCompleteObserver) {
  85780. this.onCompleteObservable.remove(this._onCompleteObserver);
  85781. }
  85782. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  85783. },
  85784. enumerable: true,
  85785. configurable: true
  85786. });
  85787. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  85788. set: function (callback) {
  85789. if (this._onDisposeObserver) {
  85790. this.onDisposeObservable.remove(this._onDisposeObserver);
  85791. }
  85792. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85793. },
  85794. enumerable: true,
  85795. configurable: true
  85796. });
  85797. /**
  85798. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  85799. */
  85800. GLTFFileLoader.prototype.dispose = function () {
  85801. if (this._loader) {
  85802. this._loader.dispose();
  85803. this._loader = null;
  85804. }
  85805. this.onParsedObservable.clear();
  85806. this.onMeshLoadedObservable.clear();
  85807. this.onTextureLoadedObservable.clear();
  85808. this.onMaterialLoadedObservable.clear();
  85809. this.onCompleteObservable.clear();
  85810. this.onDisposeObservable.notifyObservers(this);
  85811. this.onDisposeObservable.clear();
  85812. };
  85813. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85814. try {
  85815. var loaderData = this._parse(data);
  85816. this._loader = this._getLoader(loaderData);
  85817. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85818. }
  85819. catch (e) {
  85820. if (onError) {
  85821. onError(e.message, e);
  85822. }
  85823. else {
  85824. BABYLON.Tools.Error(e.message);
  85825. }
  85826. }
  85827. };
  85828. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85829. try {
  85830. var loaderData = this._parse(data);
  85831. this._loader = this._getLoader(loaderData);
  85832. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85833. }
  85834. catch (e) {
  85835. if (onError) {
  85836. onError(e.message, e);
  85837. }
  85838. else {
  85839. BABYLON.Tools.Error(e.message);
  85840. }
  85841. }
  85842. };
  85843. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85844. try {
  85845. var loaderData = this._parse(data);
  85846. this._loader = this._getLoader(loaderData);
  85847. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  85848. var container = new BABYLON.AssetContainer(scene);
  85849. Array.prototype.push.apply(container.meshes, meshes);
  85850. Array.prototype.push.apply(container.particleSystems, particleSystems);
  85851. Array.prototype.push.apply(container.skeletons, skeletons);
  85852. container.removeAllFromScene();
  85853. onSuccess(container);
  85854. }, onProgress, onError);
  85855. }
  85856. catch (e) {
  85857. if (onError) {
  85858. onError(e.message, e);
  85859. }
  85860. else {
  85861. BABYLON.Tools.Error(e.message);
  85862. }
  85863. }
  85864. };
  85865. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  85866. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  85867. };
  85868. GLTFFileLoader.prototype.createPlugin = function () {
  85869. return new GLTFFileLoader();
  85870. };
  85871. GLTFFileLoader.prototype._parse = function (data) {
  85872. var parsedData;
  85873. if (data instanceof ArrayBuffer) {
  85874. parsedData = GLTFFileLoader._parseBinary(data);
  85875. }
  85876. else {
  85877. parsedData = {
  85878. json: JSON.parse(data),
  85879. bin: null
  85880. };
  85881. }
  85882. this.onParsedObservable.notifyObservers(parsedData);
  85883. return parsedData;
  85884. };
  85885. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  85886. var _this = this;
  85887. var loaderVersion = { major: 2, minor: 0 };
  85888. var asset = loaderData.json.asset || {};
  85889. var version = GLTFFileLoader._parseVersion(asset.version);
  85890. if (!version) {
  85891. throw new Error("Invalid version: " + asset.version);
  85892. }
  85893. if (asset.minVersion !== undefined) {
  85894. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  85895. if (!minVersion) {
  85896. throw new Error("Invalid minimum version: " + asset.minVersion);
  85897. }
  85898. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  85899. throw new Error("Incompatible minimum version: " + asset.minVersion);
  85900. }
  85901. }
  85902. var createLoaders = {
  85903. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  85904. 2: GLTFFileLoader.CreateGLTFLoaderV2
  85905. };
  85906. var createLoader = createLoaders[version.major];
  85907. if (!createLoader) {
  85908. throw new Error("Unsupported version: " + asset.version);
  85909. }
  85910. var loader = createLoader();
  85911. loader.coordinateSystemMode = this.coordinateSystemMode;
  85912. loader.animationStartMode = this.animationStartMode;
  85913. loader.compileMaterials = this.compileMaterials;
  85914. loader.useClipPlane = this.useClipPlane;
  85915. loader.compileShadowGenerators = this.compileShadowGenerators;
  85916. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  85917. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  85918. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  85919. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  85920. return loader;
  85921. };
  85922. GLTFFileLoader._parseBinary = function (data) {
  85923. var Binary = {
  85924. Magic: 0x46546C67
  85925. };
  85926. var binaryReader = new BinaryReader(data);
  85927. var magic = binaryReader.readUint32();
  85928. if (magic !== Binary.Magic) {
  85929. throw new Error("Unexpected magic: " + magic);
  85930. }
  85931. var version = binaryReader.readUint32();
  85932. switch (version) {
  85933. case 1: return GLTFFileLoader._parseV1(binaryReader);
  85934. case 2: return GLTFFileLoader._parseV2(binaryReader);
  85935. }
  85936. throw new Error("Unsupported version: " + version);
  85937. };
  85938. GLTFFileLoader._parseV1 = function (binaryReader) {
  85939. var ContentFormat = {
  85940. JSON: 0
  85941. };
  85942. var length = binaryReader.readUint32();
  85943. if (length != binaryReader.getLength()) {
  85944. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85945. }
  85946. var contentLength = binaryReader.readUint32();
  85947. var contentFormat = binaryReader.readUint32();
  85948. var content;
  85949. switch (contentFormat) {
  85950. case ContentFormat.JSON: {
  85951. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  85952. break;
  85953. }
  85954. default: {
  85955. throw new Error("Unexpected content format: " + contentFormat);
  85956. }
  85957. }
  85958. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  85959. var body = binaryReader.readUint8Array(bytesRemaining);
  85960. return {
  85961. json: content,
  85962. bin: body
  85963. };
  85964. };
  85965. GLTFFileLoader._parseV2 = function (binaryReader) {
  85966. var ChunkFormat = {
  85967. JSON: 0x4E4F534A,
  85968. BIN: 0x004E4942
  85969. };
  85970. var length = binaryReader.readUint32();
  85971. if (length !== binaryReader.getLength()) {
  85972. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85973. }
  85974. // JSON chunk
  85975. var chunkLength = binaryReader.readUint32();
  85976. var chunkFormat = binaryReader.readUint32();
  85977. if (chunkFormat !== ChunkFormat.JSON) {
  85978. throw new Error("First chunk format is not JSON");
  85979. }
  85980. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  85981. // Look for BIN chunk
  85982. var bin = null;
  85983. while (binaryReader.getPosition() < binaryReader.getLength()) {
  85984. var chunkLength_1 = binaryReader.readUint32();
  85985. var chunkFormat_1 = binaryReader.readUint32();
  85986. switch (chunkFormat_1) {
  85987. case ChunkFormat.JSON: {
  85988. throw new Error("Unexpected JSON chunk");
  85989. }
  85990. case ChunkFormat.BIN: {
  85991. bin = binaryReader.readUint8Array(chunkLength_1);
  85992. break;
  85993. }
  85994. default: {
  85995. // ignore unrecognized chunkFormat
  85996. binaryReader.skipBytes(chunkLength_1);
  85997. break;
  85998. }
  85999. }
  86000. }
  86001. return {
  86002. json: json,
  86003. bin: bin
  86004. };
  86005. };
  86006. GLTFFileLoader._parseVersion = function (version) {
  86007. if (version === "1.0" || version === "1.0.1") {
  86008. return {
  86009. major: 1,
  86010. minor: 0
  86011. };
  86012. }
  86013. var match = (version + "").match(/^(\d+)\.(\d+)/);
  86014. if (!match) {
  86015. return null;
  86016. }
  86017. return {
  86018. major: parseInt(match[1]),
  86019. minor: parseInt(match[2])
  86020. };
  86021. };
  86022. GLTFFileLoader._compareVersion = function (a, b) {
  86023. if (a.major > b.major)
  86024. return 1;
  86025. if (a.major < b.major)
  86026. return -1;
  86027. if (a.minor > b.minor)
  86028. return 1;
  86029. if (a.minor < b.minor)
  86030. return -1;
  86031. return 0;
  86032. };
  86033. GLTFFileLoader._decodeBufferToText = function (buffer) {
  86034. var result = "";
  86035. var length = buffer.byteLength;
  86036. for (var i = 0; i < length; i++) {
  86037. result += String.fromCharCode(buffer[i]);
  86038. }
  86039. return result;
  86040. };
  86041. // #endregion
  86042. // #region V1 options
  86043. GLTFFileLoader.IncrementalLoading = true;
  86044. GLTFFileLoader.HomogeneousCoordinates = false;
  86045. return GLTFFileLoader;
  86046. }());
  86047. BABYLON.GLTFFileLoader = GLTFFileLoader;
  86048. var BinaryReader = /** @class */ (function () {
  86049. function BinaryReader(arrayBuffer) {
  86050. this._arrayBuffer = arrayBuffer;
  86051. this._dataView = new DataView(arrayBuffer);
  86052. this._byteOffset = 0;
  86053. }
  86054. BinaryReader.prototype.getPosition = function () {
  86055. return this._byteOffset;
  86056. };
  86057. BinaryReader.prototype.getLength = function () {
  86058. return this._arrayBuffer.byteLength;
  86059. };
  86060. BinaryReader.prototype.readUint32 = function () {
  86061. var value = this._dataView.getUint32(this._byteOffset, true);
  86062. this._byteOffset += 4;
  86063. return value;
  86064. };
  86065. BinaryReader.prototype.readUint8Array = function (length) {
  86066. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  86067. this._byteOffset += length;
  86068. return value;
  86069. };
  86070. BinaryReader.prototype.skipBytes = function (length) {
  86071. this._byteOffset += length;
  86072. };
  86073. return BinaryReader;
  86074. }());
  86075. if (BABYLON.SceneLoader) {
  86076. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  86077. }
  86078. })(BABYLON || (BABYLON = {}));
  86079. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  86080. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86081. var BABYLON;
  86082. (function (BABYLON) {
  86083. var GLTF1;
  86084. (function (GLTF1) {
  86085. /**
  86086. * Enums
  86087. */
  86088. var EComponentType;
  86089. (function (EComponentType) {
  86090. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  86091. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86092. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  86093. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86094. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  86095. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  86096. var EShaderType;
  86097. (function (EShaderType) {
  86098. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  86099. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  86100. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  86101. var EParameterType;
  86102. (function (EParameterType) {
  86103. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  86104. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86105. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  86106. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86107. EParameterType[EParameterType["INT"] = 5124] = "INT";
  86108. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  86109. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  86110. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  86111. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  86112. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  86113. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  86114. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  86115. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  86116. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  86117. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  86118. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  86119. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  86120. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  86121. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  86122. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  86123. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  86124. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  86125. var ETextureWrapMode;
  86126. (function (ETextureWrapMode) {
  86127. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  86128. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  86129. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  86130. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  86131. var ETextureFilterType;
  86132. (function (ETextureFilterType) {
  86133. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  86134. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  86135. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  86136. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  86137. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  86138. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  86139. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  86140. var ETextureFormat;
  86141. (function (ETextureFormat) {
  86142. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  86143. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  86144. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  86145. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  86146. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  86147. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  86148. var ECullingType;
  86149. (function (ECullingType) {
  86150. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  86151. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  86152. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  86153. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  86154. var EBlendingFunction;
  86155. (function (EBlendingFunction) {
  86156. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  86157. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  86158. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  86159. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  86160. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  86161. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  86162. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  86163. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  86164. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  86165. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  86166. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  86167. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  86168. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  86169. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  86170. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  86171. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  86172. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86173. })(BABYLON || (BABYLON = {}));
  86174. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  86175. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86176. var BABYLON;
  86177. (function (BABYLON) {
  86178. var GLTF1;
  86179. (function (GLTF1) {
  86180. /**
  86181. * Tokenizer. Used for shaders compatibility
  86182. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  86183. */
  86184. var ETokenType;
  86185. (function (ETokenType) {
  86186. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  86187. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  86188. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  86189. })(ETokenType || (ETokenType = {}));
  86190. var Tokenizer = /** @class */ (function () {
  86191. function Tokenizer(toParse) {
  86192. this._pos = 0;
  86193. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  86194. this._toParse = toParse;
  86195. this._maxPos = toParse.length;
  86196. }
  86197. Tokenizer.prototype.getNextToken = function () {
  86198. if (this.isEnd())
  86199. return ETokenType.END_OF_INPUT;
  86200. this.currentString = this.read();
  86201. this.currentToken = ETokenType.UNKNOWN;
  86202. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  86203. this.currentToken = ETokenType.IDENTIFIER;
  86204. this.currentIdentifier = this.currentString;
  86205. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  86206. this.currentIdentifier += this.currentString;
  86207. this.forward();
  86208. }
  86209. }
  86210. return this.currentToken;
  86211. };
  86212. Tokenizer.prototype.peek = function () {
  86213. return this._toParse[this._pos];
  86214. };
  86215. Tokenizer.prototype.read = function () {
  86216. return this._toParse[this._pos++];
  86217. };
  86218. Tokenizer.prototype.forward = function () {
  86219. this._pos++;
  86220. };
  86221. Tokenizer.prototype.isEnd = function () {
  86222. return this._pos >= this._maxPos;
  86223. };
  86224. return Tokenizer;
  86225. }());
  86226. /**
  86227. * Values
  86228. */
  86229. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  86230. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  86231. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  86232. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  86233. /**
  86234. * Parse
  86235. */
  86236. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  86237. for (var buf in parsedBuffers) {
  86238. var parsedBuffer = parsedBuffers[buf];
  86239. gltfRuntime.buffers[buf] = parsedBuffer;
  86240. gltfRuntime.buffersCount++;
  86241. }
  86242. };
  86243. var parseShaders = function (parsedShaders, gltfRuntime) {
  86244. for (var sha in parsedShaders) {
  86245. var parsedShader = parsedShaders[sha];
  86246. gltfRuntime.shaders[sha] = parsedShader;
  86247. gltfRuntime.shaderscount++;
  86248. }
  86249. };
  86250. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  86251. for (var object in parsedObjects) {
  86252. var parsedObject = parsedObjects[object];
  86253. gltfRuntime[runtimeProperty][object] = parsedObject;
  86254. }
  86255. };
  86256. /**
  86257. * Utils
  86258. */
  86259. var normalizeUVs = function (buffer) {
  86260. if (!buffer) {
  86261. return;
  86262. }
  86263. for (var i = 0; i < buffer.length / 2; i++) {
  86264. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  86265. }
  86266. };
  86267. var getAttribute = function (attributeParameter) {
  86268. if (attributeParameter.semantic === "NORMAL") {
  86269. return "normal";
  86270. }
  86271. else if (attributeParameter.semantic === "POSITION") {
  86272. return "position";
  86273. }
  86274. else if (attributeParameter.semantic === "JOINT") {
  86275. return "matricesIndices";
  86276. }
  86277. else if (attributeParameter.semantic === "WEIGHT") {
  86278. return "matricesWeights";
  86279. }
  86280. else if (attributeParameter.semantic === "COLOR") {
  86281. return "color";
  86282. }
  86283. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  86284. var channel = Number(attributeParameter.semantic.split("_")[1]);
  86285. return "uv" + (channel === 0 ? "" : channel + 1);
  86286. }
  86287. return null;
  86288. };
  86289. /**
  86290. * Loads and creates animations
  86291. */
  86292. var loadAnimations = function (gltfRuntime) {
  86293. for (var anim in gltfRuntime.animations) {
  86294. var animation = gltfRuntime.animations[anim];
  86295. if (!animation.channels || !animation.samplers) {
  86296. continue;
  86297. }
  86298. var lastAnimation = null;
  86299. for (var i = 0; i < animation.channels.length; i++) {
  86300. // Get parameters and load buffers
  86301. var channel = animation.channels[i];
  86302. var sampler = animation.samplers[channel.sampler];
  86303. if (!sampler) {
  86304. continue;
  86305. }
  86306. var inputData = null;
  86307. var outputData = null;
  86308. if (animation.parameters) {
  86309. inputData = animation.parameters[sampler.input];
  86310. outputData = animation.parameters[sampler.output];
  86311. }
  86312. else {
  86313. inputData = sampler.input;
  86314. outputData = sampler.output;
  86315. }
  86316. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  86317. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  86318. var targetID = channel.target.id;
  86319. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  86320. if (targetNode === null) {
  86321. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  86322. }
  86323. if (targetNode === null) {
  86324. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  86325. continue;
  86326. }
  86327. var isBone = targetNode instanceof BABYLON.Bone;
  86328. // Get target path (position, rotation or scaling)
  86329. var targetPath = channel.target.path;
  86330. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  86331. if (targetPathIndex !== -1) {
  86332. targetPath = babylonAnimationPaths[targetPathIndex];
  86333. }
  86334. // Determine animation type
  86335. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  86336. if (!isBone) {
  86337. if (targetPath === "rotationQuaternion") {
  86338. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  86339. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  86340. }
  86341. else {
  86342. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  86343. }
  86344. }
  86345. // Create animation and key frames
  86346. var babylonAnimation = null;
  86347. var keys = [];
  86348. var arrayOffset = 0;
  86349. var modifyKey = false;
  86350. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  86351. babylonAnimation = lastAnimation;
  86352. modifyKey = true;
  86353. }
  86354. if (!modifyKey) {
  86355. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  86356. }
  86357. // For each frame
  86358. for (var j = 0; j < bufferInput.length; j++) {
  86359. var value = null;
  86360. if (targetPath === "rotationQuaternion") {
  86361. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  86362. arrayOffset += 4;
  86363. }
  86364. else {
  86365. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  86366. arrayOffset += 3;
  86367. }
  86368. if (isBone) {
  86369. var bone = targetNode;
  86370. var translation = BABYLON.Vector3.Zero();
  86371. var rotationQuaternion = new BABYLON.Quaternion();
  86372. var scaling = BABYLON.Vector3.Zero();
  86373. // Warning on decompose
  86374. var mat = bone.getBaseMatrix();
  86375. if (modifyKey && lastAnimation) {
  86376. mat = lastAnimation.getKeys()[j].value;
  86377. }
  86378. mat.decompose(scaling, rotationQuaternion, translation);
  86379. if (targetPath === "position") {
  86380. translation = value;
  86381. }
  86382. else if (targetPath === "rotationQuaternion") {
  86383. rotationQuaternion = value;
  86384. }
  86385. else {
  86386. scaling = value;
  86387. }
  86388. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  86389. }
  86390. if (!modifyKey) {
  86391. keys.push({
  86392. frame: bufferInput[j],
  86393. value: value
  86394. });
  86395. }
  86396. else if (lastAnimation) {
  86397. lastAnimation.getKeys()[j].value = value;
  86398. }
  86399. }
  86400. // Finish
  86401. if (!modifyKey && babylonAnimation) {
  86402. babylonAnimation.setKeys(keys);
  86403. targetNode.animations.push(babylonAnimation);
  86404. }
  86405. lastAnimation = babylonAnimation;
  86406. gltfRuntime.scene.stopAnimation(targetNode);
  86407. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  86408. }
  86409. }
  86410. };
  86411. /**
  86412. * Returns the bones transformation matrix
  86413. */
  86414. var configureBoneTransformation = function (node) {
  86415. var mat = null;
  86416. if (node.translation || node.rotation || node.scale) {
  86417. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  86418. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  86419. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  86420. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  86421. }
  86422. else {
  86423. mat = BABYLON.Matrix.FromArray(node.matrix);
  86424. }
  86425. return mat;
  86426. };
  86427. /**
  86428. * Returns the parent bone
  86429. */
  86430. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  86431. // Try to find
  86432. for (var i = 0; i < newSkeleton.bones.length; i++) {
  86433. if (newSkeleton.bones[i].name === jointName) {
  86434. return newSkeleton.bones[i];
  86435. }
  86436. }
  86437. // Not found, search in gltf nodes
  86438. var nodes = gltfRuntime.nodes;
  86439. for (var nde in nodes) {
  86440. var node = nodes[nde];
  86441. if (!node.jointName) {
  86442. continue;
  86443. }
  86444. var children = node.children;
  86445. for (var i = 0; i < children.length; i++) {
  86446. var child = gltfRuntime.nodes[children[i]];
  86447. if (!child.jointName) {
  86448. continue;
  86449. }
  86450. if (child.jointName === jointName) {
  86451. var mat = configureBoneTransformation(node);
  86452. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  86453. bone.id = nde;
  86454. return bone;
  86455. }
  86456. }
  86457. }
  86458. return null;
  86459. };
  86460. /**
  86461. * Returns the appropriate root node
  86462. */
  86463. var getNodeToRoot = function (nodesToRoot, id) {
  86464. for (var i = 0; i < nodesToRoot.length; i++) {
  86465. var nodeToRoot = nodesToRoot[i];
  86466. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  86467. var child = nodeToRoot.node.children[j];
  86468. if (child === id) {
  86469. return nodeToRoot.bone;
  86470. }
  86471. }
  86472. }
  86473. return null;
  86474. };
  86475. /**
  86476. * Returns the node with the joint name
  86477. */
  86478. var getJointNode = function (gltfRuntime, jointName) {
  86479. var nodes = gltfRuntime.nodes;
  86480. var node = nodes[jointName];
  86481. if (node) {
  86482. return {
  86483. node: node,
  86484. id: jointName
  86485. };
  86486. }
  86487. for (var nde in nodes) {
  86488. node = nodes[nde];
  86489. if (node.jointName === jointName) {
  86490. return {
  86491. node: node,
  86492. id: nde
  86493. };
  86494. }
  86495. }
  86496. return null;
  86497. };
  86498. /**
  86499. * Checks if a nodes is in joints
  86500. */
  86501. var nodeIsInJoints = function (skins, id) {
  86502. for (var i = 0; i < skins.jointNames.length; i++) {
  86503. if (skins.jointNames[i] === id) {
  86504. return true;
  86505. }
  86506. }
  86507. return false;
  86508. };
  86509. /**
  86510. * Fills the nodes to root for bones and builds hierarchy
  86511. */
  86512. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  86513. // Creates nodes for root
  86514. for (var nde in gltfRuntime.nodes) {
  86515. var node = gltfRuntime.nodes[nde];
  86516. var id = nde;
  86517. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  86518. continue;
  86519. }
  86520. // Create node to root bone
  86521. var mat = configureBoneTransformation(node);
  86522. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  86523. bone.id = id;
  86524. nodesToRoot.push({ bone: bone, node: node, id: id });
  86525. }
  86526. // Parenting
  86527. for (var i = 0; i < nodesToRoot.length; i++) {
  86528. var nodeToRoot = nodesToRoot[i];
  86529. var children = nodeToRoot.node.children;
  86530. for (var j = 0; j < children.length; j++) {
  86531. var child = null;
  86532. for (var k = 0; k < nodesToRoot.length; k++) {
  86533. if (nodesToRoot[k].id === children[j]) {
  86534. child = nodesToRoot[k];
  86535. break;
  86536. }
  86537. }
  86538. if (child) {
  86539. child.bone._parent = nodeToRoot.bone;
  86540. nodeToRoot.bone.children.push(child.bone);
  86541. }
  86542. }
  86543. }
  86544. };
  86545. /**
  86546. * Imports a skeleton
  86547. */
  86548. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  86549. if (!newSkeleton) {
  86550. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  86551. }
  86552. if (!skins.babylonSkeleton) {
  86553. return newSkeleton;
  86554. }
  86555. // Find the root bones
  86556. var nodesToRoot = [];
  86557. var nodesToRootToAdd = [];
  86558. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  86559. newSkeleton.bones = [];
  86560. // Joints
  86561. for (var i = 0; i < skins.jointNames.length; i++) {
  86562. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86563. if (!jointNode) {
  86564. continue;
  86565. }
  86566. var node = jointNode.node;
  86567. if (!node) {
  86568. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  86569. continue;
  86570. }
  86571. var id = jointNode.id;
  86572. // Optimize, if the bone already exists...
  86573. var existingBone = gltfRuntime.scene.getBoneByID(id);
  86574. if (existingBone) {
  86575. newSkeleton.bones.push(existingBone);
  86576. continue;
  86577. }
  86578. // Search for parent bone
  86579. var foundBone = false;
  86580. var parentBone = null;
  86581. for (var j = 0; j < i; j++) {
  86582. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  86583. if (!jointNode_1) {
  86584. continue;
  86585. }
  86586. var joint = jointNode_1.node;
  86587. if (!joint) {
  86588. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  86589. continue;
  86590. }
  86591. var children = joint.children;
  86592. if (!children) {
  86593. continue;
  86594. }
  86595. foundBone = false;
  86596. for (var k = 0; k < children.length; k++) {
  86597. if (children[k] === id) {
  86598. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  86599. foundBone = true;
  86600. break;
  86601. }
  86602. }
  86603. if (foundBone) {
  86604. break;
  86605. }
  86606. }
  86607. // Create bone
  86608. var mat = configureBoneTransformation(node);
  86609. if (!parentBone && nodesToRoot.length > 0) {
  86610. parentBone = getNodeToRoot(nodesToRoot, id);
  86611. if (parentBone) {
  86612. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  86613. nodesToRootToAdd.push(parentBone);
  86614. }
  86615. }
  86616. }
  86617. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  86618. bone.id = id;
  86619. }
  86620. // Polish
  86621. var bones = newSkeleton.bones;
  86622. newSkeleton.bones = [];
  86623. for (var i = 0; i < skins.jointNames.length; i++) {
  86624. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86625. if (!jointNode) {
  86626. continue;
  86627. }
  86628. for (var j = 0; j < bones.length; j++) {
  86629. if (bones[j].id === jointNode.id) {
  86630. newSkeleton.bones.push(bones[j]);
  86631. break;
  86632. }
  86633. }
  86634. }
  86635. newSkeleton.prepare();
  86636. // Finish
  86637. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  86638. newSkeleton.bones.push(nodesToRootToAdd[i]);
  86639. }
  86640. return newSkeleton;
  86641. };
  86642. /**
  86643. * Imports a mesh and its geometries
  86644. */
  86645. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  86646. if (!newMesh) {
  86647. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86648. newMesh.id = id;
  86649. }
  86650. if (!node.babylonNode) {
  86651. return newMesh;
  86652. }
  86653. var subMaterials = [];
  86654. var vertexData = new BABYLON.VertexData();
  86655. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  86656. var verticesStarts = new Array();
  86657. var verticesCounts = new Array();
  86658. var indexStarts = new Array();
  86659. var indexCounts = new Array();
  86660. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86661. var meshID = meshes[meshIndex];
  86662. var mesh = gltfRuntime.meshes[meshID];
  86663. if (!mesh) {
  86664. continue;
  86665. }
  86666. // Positions, normals and UVs
  86667. for (var i = 0; i < mesh.primitives.length; i++) {
  86668. // Temporary vertex data
  86669. var tempVertexData = new BABYLON.VertexData();
  86670. var primitive = mesh.primitives[i];
  86671. if (primitive.mode !== 4) {
  86672. // continue;
  86673. }
  86674. var attributes = primitive.attributes;
  86675. var accessor = null;
  86676. var buffer = null;
  86677. // Set positions, normal and uvs
  86678. for (var semantic in attributes) {
  86679. // Link accessor and buffer view
  86680. accessor = gltfRuntime.accessors[attributes[semantic]];
  86681. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86682. if (semantic === "NORMAL") {
  86683. tempVertexData.normals = new Float32Array(buffer.length);
  86684. tempVertexData.normals.set(buffer);
  86685. }
  86686. else if (semantic === "POSITION") {
  86687. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  86688. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  86689. for (var j = 0; j < buffer.length; j += 4) {
  86690. tempVertexData.positions[j] = buffer[j];
  86691. tempVertexData.positions[j + 1] = buffer[j + 1];
  86692. tempVertexData.positions[j + 2] = buffer[j + 2];
  86693. }
  86694. }
  86695. else {
  86696. tempVertexData.positions = new Float32Array(buffer.length);
  86697. tempVertexData.positions.set(buffer);
  86698. }
  86699. verticesCounts.push(tempVertexData.positions.length);
  86700. }
  86701. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  86702. var channel = Number(semantic.split("_")[1]);
  86703. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  86704. var uvs = new Float32Array(buffer.length);
  86705. uvs.set(buffer);
  86706. normalizeUVs(uvs);
  86707. tempVertexData.set(uvs, uvKind);
  86708. }
  86709. else if (semantic === "JOINT") {
  86710. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  86711. tempVertexData.matricesIndices.set(buffer);
  86712. }
  86713. else if (semantic === "WEIGHT") {
  86714. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  86715. tempVertexData.matricesWeights.set(buffer);
  86716. }
  86717. else if (semantic === "COLOR") {
  86718. tempVertexData.colors = new Float32Array(buffer.length);
  86719. tempVertexData.colors.set(buffer);
  86720. }
  86721. }
  86722. // Indices
  86723. accessor = gltfRuntime.accessors[primitive.indices];
  86724. if (accessor) {
  86725. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86726. tempVertexData.indices = new Int32Array(buffer.length);
  86727. tempVertexData.indices.set(buffer);
  86728. indexCounts.push(tempVertexData.indices.length);
  86729. }
  86730. else {
  86731. // Set indices on the fly
  86732. var indices = [];
  86733. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  86734. indices.push(j);
  86735. }
  86736. tempVertexData.indices = new Int32Array(indices);
  86737. indexCounts.push(tempVertexData.indices.length);
  86738. }
  86739. vertexData.merge(tempVertexData);
  86740. // Sub material
  86741. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  86742. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  86743. // Update vertices start and index start
  86744. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  86745. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  86746. }
  86747. }
  86748. var material;
  86749. if (subMaterials.length > 1) {
  86750. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  86751. material.subMaterials = subMaterials;
  86752. }
  86753. else {
  86754. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  86755. }
  86756. if (subMaterials.length === 1) {
  86757. material = subMaterials[0];
  86758. }
  86759. if (!newMesh.material) {
  86760. newMesh.material = material;
  86761. }
  86762. // Apply geometry
  86763. geometry.setAllVerticesData(vertexData, false);
  86764. newMesh.computeWorldMatrix(true);
  86765. // Apply submeshes
  86766. newMesh.subMeshes = [];
  86767. var index = 0;
  86768. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86769. var meshID = meshes[meshIndex];
  86770. var mesh = gltfRuntime.meshes[meshID];
  86771. if (!mesh) {
  86772. continue;
  86773. }
  86774. for (var i = 0; i < mesh.primitives.length; i++) {
  86775. if (mesh.primitives[i].mode !== 4) {
  86776. //continue;
  86777. }
  86778. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  86779. index++;
  86780. }
  86781. }
  86782. // Finish
  86783. return newMesh;
  86784. };
  86785. /**
  86786. * Configure node transformation from position, rotation and scaling
  86787. */
  86788. var configureNode = function (newNode, position, rotation, scaling) {
  86789. if (newNode.position) {
  86790. newNode.position = position;
  86791. }
  86792. if (newNode.rotationQuaternion || newNode.rotation) {
  86793. newNode.rotationQuaternion = rotation;
  86794. }
  86795. if (newNode.scaling) {
  86796. newNode.scaling = scaling;
  86797. }
  86798. };
  86799. /**
  86800. * Configures node from transformation matrix
  86801. */
  86802. var configureNodeFromMatrix = function (newNode, node, parent) {
  86803. if (node.matrix) {
  86804. var position = new BABYLON.Vector3(0, 0, 0);
  86805. var rotation = new BABYLON.Quaternion();
  86806. var scaling = new BABYLON.Vector3(0, 0, 0);
  86807. var mat = BABYLON.Matrix.FromArray(node.matrix);
  86808. mat.decompose(scaling, rotation, position);
  86809. configureNode(newNode, position, rotation, scaling);
  86810. }
  86811. else if (node.translation && node.rotation && node.scale) {
  86812. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  86813. }
  86814. newNode.computeWorldMatrix(true);
  86815. };
  86816. /**
  86817. * Imports a node
  86818. */
  86819. var importNode = function (gltfRuntime, node, id, parent) {
  86820. var lastNode = null;
  86821. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  86822. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  86823. return null;
  86824. }
  86825. }
  86826. // Meshes
  86827. if (node.skin) {
  86828. if (node.meshes) {
  86829. var skin = gltfRuntime.skins[node.skin];
  86830. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  86831. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  86832. if (newMesh.skeleton === null) {
  86833. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  86834. if (!skin.babylonSkeleton) {
  86835. skin.babylonSkeleton = newMesh.skeleton;
  86836. }
  86837. }
  86838. lastNode = newMesh;
  86839. }
  86840. }
  86841. else if (node.meshes) {
  86842. /**
  86843. * Improve meshes property
  86844. */
  86845. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  86846. lastNode = newMesh;
  86847. }
  86848. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86849. var light = gltfRuntime.lights[node.light];
  86850. if (light) {
  86851. if (light.type === "ambient") {
  86852. var ambienLight = light[light.type];
  86853. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86854. hemiLight.name = node.name || "";
  86855. if (ambienLight.color) {
  86856. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  86857. }
  86858. lastNode = hemiLight;
  86859. }
  86860. else if (light.type === "directional") {
  86861. var directionalLight = light[light.type];
  86862. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86863. dirLight.name = node.name || "";
  86864. if (directionalLight.color) {
  86865. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  86866. }
  86867. lastNode = dirLight;
  86868. }
  86869. else if (light.type === "point") {
  86870. var pointLight = light[light.type];
  86871. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86872. ptLight.name = node.name || "";
  86873. if (pointLight.color) {
  86874. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  86875. }
  86876. lastNode = ptLight;
  86877. }
  86878. else if (light.type === "spot") {
  86879. var spotLight = light[light.type];
  86880. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  86881. spLight.name = node.name || "";
  86882. if (spotLight.color) {
  86883. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  86884. }
  86885. if (spotLight.fallOfAngle) {
  86886. spLight.angle = spotLight.fallOfAngle;
  86887. }
  86888. if (spotLight.fallOffExponent) {
  86889. spLight.exponent = spotLight.fallOffExponent;
  86890. }
  86891. lastNode = spLight;
  86892. }
  86893. }
  86894. }
  86895. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86896. var camera = gltfRuntime.cameras[node.camera];
  86897. if (camera) {
  86898. if (camera.type === "orthographic") {
  86899. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86900. orthoCamera.name = node.name || "";
  86901. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  86902. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86903. lastNode = orthoCamera;
  86904. }
  86905. else if (camera.type === "perspective") {
  86906. var perspectiveCamera = camera[camera.type];
  86907. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86908. persCamera.name = node.name || "";
  86909. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86910. if (!perspectiveCamera.aspectRatio) {
  86911. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  86912. }
  86913. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  86914. persCamera.maxZ = perspectiveCamera.zfar;
  86915. persCamera.minZ = perspectiveCamera.znear;
  86916. }
  86917. lastNode = persCamera;
  86918. }
  86919. }
  86920. }
  86921. // Empty node
  86922. if (!node.jointName) {
  86923. if (node.babylonNode) {
  86924. return node.babylonNode;
  86925. }
  86926. else if (lastNode === null) {
  86927. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86928. node.babylonNode = dummy;
  86929. lastNode = dummy;
  86930. }
  86931. }
  86932. if (lastNode !== null) {
  86933. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  86934. configureNodeFromMatrix(lastNode, node, parent);
  86935. }
  86936. else {
  86937. var translation = node.translation || [0, 0, 0];
  86938. var rotation = node.rotation || [0, 0, 0, 1];
  86939. var scale = node.scale || [1, 1, 1];
  86940. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  86941. }
  86942. lastNode.updateCache(true);
  86943. node.babylonNode = lastNode;
  86944. }
  86945. return lastNode;
  86946. };
  86947. /**
  86948. * Traverses nodes and creates them
  86949. */
  86950. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  86951. if (meshIncluded === void 0) { meshIncluded = false; }
  86952. var node = gltfRuntime.nodes[id];
  86953. var newNode = null;
  86954. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  86955. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  86956. meshIncluded = true;
  86957. }
  86958. else {
  86959. meshIncluded = false;
  86960. }
  86961. }
  86962. else {
  86963. meshIncluded = true;
  86964. }
  86965. if (!node.jointName && meshIncluded) {
  86966. newNode = importNode(gltfRuntime, node, id, parent);
  86967. if (newNode !== null) {
  86968. newNode.id = id;
  86969. newNode.parent = parent;
  86970. }
  86971. }
  86972. if (node.children) {
  86973. for (var i = 0; i < node.children.length; i++) {
  86974. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  86975. }
  86976. }
  86977. };
  86978. /**
  86979. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  86980. */
  86981. var postLoad = function (gltfRuntime) {
  86982. // Nodes
  86983. var currentScene = gltfRuntime.currentScene;
  86984. if (currentScene) {
  86985. for (var i = 0; i < currentScene.nodes.length; i++) {
  86986. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86987. }
  86988. }
  86989. else {
  86990. for (var thing in gltfRuntime.scenes) {
  86991. currentScene = gltfRuntime.scenes[thing];
  86992. for (var i = 0; i < currentScene.nodes.length; i++) {
  86993. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86994. }
  86995. }
  86996. }
  86997. // Set animations
  86998. loadAnimations(gltfRuntime);
  86999. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  87000. var skeleton = gltfRuntime.scene.skeletons[i];
  87001. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  87002. }
  87003. };
  87004. /**
  87005. * onBind shaderrs callback to set uniforms and matrices
  87006. */
  87007. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  87008. var materialValues = material.values || technique.parameters;
  87009. for (var unif in unTreatedUniforms) {
  87010. var uniform = unTreatedUniforms[unif];
  87011. var type = uniform.type;
  87012. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  87013. if (uniform.semantic && !uniform.source && !uniform.node) {
  87014. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  87015. }
  87016. else if (uniform.semantic && (uniform.source || uniform.node)) {
  87017. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  87018. if (source === null) {
  87019. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  87020. }
  87021. if (source === null) {
  87022. continue;
  87023. }
  87024. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  87025. }
  87026. }
  87027. else {
  87028. var value = materialValues[technique.uniforms[unif]];
  87029. if (!value) {
  87030. continue;
  87031. }
  87032. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  87033. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  87034. if (texture === null || texture === undefined) {
  87035. continue;
  87036. }
  87037. shaderMaterial.getEffect().setTexture(unif, texture);
  87038. }
  87039. else {
  87040. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  87041. }
  87042. }
  87043. }
  87044. onSuccess(shaderMaterial);
  87045. };
  87046. /**
  87047. * Prepare uniforms to send the only one time
  87048. * Loads the appropriate textures
  87049. */
  87050. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  87051. var materialValues = material.values || technique.parameters;
  87052. var techniqueUniforms = technique.uniforms;
  87053. /**
  87054. * Prepare values here (not matrices)
  87055. */
  87056. for (var unif in unTreatedUniforms) {
  87057. var uniform = unTreatedUniforms[unif];
  87058. var type = uniform.type;
  87059. var value = materialValues[techniqueUniforms[unif]];
  87060. if (value === undefined) {
  87061. // In case the value is the same for all materials
  87062. value = uniform.value;
  87063. }
  87064. if (!value) {
  87065. continue;
  87066. }
  87067. var onLoadTexture = function (uniformName) {
  87068. return function (texture) {
  87069. if (uniform.value && uniformName) {
  87070. // Static uniform
  87071. shaderMaterial.setTexture(uniformName, texture);
  87072. delete unTreatedUniforms[uniformName];
  87073. }
  87074. };
  87075. };
  87076. // Texture (sampler2D)
  87077. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  87078. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  87079. }
  87080. else {
  87081. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  87082. // Static uniform
  87083. delete unTreatedUniforms[unif];
  87084. }
  87085. }
  87086. }
  87087. };
  87088. /**
  87089. * Shader compilation failed
  87090. */
  87091. var onShaderCompileError = function (program, shaderMaterial, onError) {
  87092. return function (effect, error) {
  87093. shaderMaterial.dispose(true);
  87094. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  87095. };
  87096. };
  87097. /**
  87098. * Shader compilation success
  87099. */
  87100. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  87101. return function (_) {
  87102. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  87103. shaderMaterial.onBind = function (mesh) {
  87104. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  87105. };
  87106. };
  87107. };
  87108. /**
  87109. * Returns the appropriate uniform if already handled by babylon
  87110. */
  87111. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  87112. for (var unif in technique.uniforms) {
  87113. var uniform = technique.uniforms[unif];
  87114. var uniformParameter = technique.parameters[uniform];
  87115. if (tokenizer.currentIdentifier === unif) {
  87116. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  87117. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  87118. if (transformIndex !== -1) {
  87119. delete unTreatedUniforms[unif];
  87120. return babylonTransforms[transformIndex];
  87121. }
  87122. }
  87123. }
  87124. }
  87125. return tokenizer.currentIdentifier;
  87126. };
  87127. /**
  87128. * All shaders loaded. Create materials one by one
  87129. */
  87130. var importMaterials = function (gltfRuntime) {
  87131. // Create materials
  87132. for (var mat in gltfRuntime.materials) {
  87133. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  87134. }
  87135. };
  87136. /**
  87137. * Implementation of the base glTF spec
  87138. */
  87139. var GLTFLoaderBase = /** @class */ (function () {
  87140. function GLTFLoaderBase() {
  87141. }
  87142. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  87143. var gltfRuntime = {
  87144. extensions: {},
  87145. accessors: {},
  87146. buffers: {},
  87147. bufferViews: {},
  87148. meshes: {},
  87149. lights: {},
  87150. cameras: {},
  87151. nodes: {},
  87152. images: {},
  87153. textures: {},
  87154. shaders: {},
  87155. programs: {},
  87156. samplers: {},
  87157. techniques: {},
  87158. materials: {},
  87159. animations: {},
  87160. skins: {},
  87161. extensionsUsed: [],
  87162. scenes: {},
  87163. buffersCount: 0,
  87164. shaderscount: 0,
  87165. scene: scene,
  87166. rootUrl: rootUrl,
  87167. loadedBufferCount: 0,
  87168. loadedBufferViews: {},
  87169. loadedShaderCount: 0,
  87170. importOnlyMeshes: false,
  87171. dummyNodes: []
  87172. };
  87173. // Parse
  87174. if (parsedData.extensions) {
  87175. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  87176. }
  87177. if (parsedData.extensionsUsed) {
  87178. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  87179. }
  87180. if (parsedData.buffers) {
  87181. parseBuffers(parsedData.buffers, gltfRuntime);
  87182. }
  87183. if (parsedData.bufferViews) {
  87184. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  87185. }
  87186. if (parsedData.accessors) {
  87187. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  87188. }
  87189. if (parsedData.meshes) {
  87190. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  87191. }
  87192. if (parsedData.lights) {
  87193. parseObject(parsedData.lights, "lights", gltfRuntime);
  87194. }
  87195. if (parsedData.cameras) {
  87196. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  87197. }
  87198. if (parsedData.nodes) {
  87199. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  87200. }
  87201. if (parsedData.images) {
  87202. parseObject(parsedData.images, "images", gltfRuntime);
  87203. }
  87204. if (parsedData.textures) {
  87205. parseObject(parsedData.textures, "textures", gltfRuntime);
  87206. }
  87207. if (parsedData.shaders) {
  87208. parseShaders(parsedData.shaders, gltfRuntime);
  87209. }
  87210. if (parsedData.programs) {
  87211. parseObject(parsedData.programs, "programs", gltfRuntime);
  87212. }
  87213. if (parsedData.samplers) {
  87214. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  87215. }
  87216. if (parsedData.techniques) {
  87217. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  87218. }
  87219. if (parsedData.materials) {
  87220. parseObject(parsedData.materials, "materials", gltfRuntime);
  87221. }
  87222. if (parsedData.animations) {
  87223. parseObject(parsedData.animations, "animations", gltfRuntime);
  87224. }
  87225. if (parsedData.skins) {
  87226. parseObject(parsedData.skins, "skins", gltfRuntime);
  87227. }
  87228. if (parsedData.scenes) {
  87229. gltfRuntime.scenes = parsedData.scenes;
  87230. }
  87231. if (parsedData.scene && parsedData.scenes) {
  87232. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  87233. }
  87234. return gltfRuntime;
  87235. };
  87236. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87237. var buffer = gltfRuntime.buffers[id];
  87238. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  87239. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  87240. }
  87241. else {
  87242. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  87243. if (request) {
  87244. onError(request.status + " " + request.statusText);
  87245. }
  87246. });
  87247. }
  87248. };
  87249. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87250. var texture = gltfRuntime.textures[id];
  87251. if (!texture || !texture.source) {
  87252. onError("");
  87253. return;
  87254. }
  87255. if (texture.babylonTexture) {
  87256. onSuccess(null);
  87257. return;
  87258. }
  87259. var source = gltfRuntime.images[texture.source];
  87260. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  87261. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  87262. }
  87263. else {
  87264. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  87265. if (request) {
  87266. onError(request.status + " " + request.statusText);
  87267. }
  87268. });
  87269. }
  87270. };
  87271. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87272. var texture = gltfRuntime.textures[id];
  87273. if (texture.babylonTexture) {
  87274. onSuccess(texture.babylonTexture);
  87275. return;
  87276. }
  87277. var sampler = gltfRuntime.samplers[texture.sampler];
  87278. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  87279. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  87280. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  87281. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  87282. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  87283. var blob = new Blob([buffer]);
  87284. var blobURL = URL.createObjectURL(blob);
  87285. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  87286. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  87287. if (sampler.wrapS !== undefined) {
  87288. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  87289. }
  87290. if (sampler.wrapT !== undefined) {
  87291. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  87292. }
  87293. newTexture.name = id;
  87294. texture.babylonTexture = newTexture;
  87295. onSuccess(newTexture);
  87296. };
  87297. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87298. var shader = gltfRuntime.shaders[id];
  87299. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  87300. var shaderString = atob(shader.uri.split(",")[1]);
  87301. onSuccess(shaderString);
  87302. }
  87303. else {
  87304. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  87305. if (request) {
  87306. onError(request.status + " " + request.statusText);
  87307. }
  87308. });
  87309. }
  87310. };
  87311. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87312. var material = gltfRuntime.materials[id];
  87313. if (!material.technique) {
  87314. if (onError) {
  87315. onError("No technique found.");
  87316. }
  87317. return;
  87318. }
  87319. var technique = gltfRuntime.techniques[material.technique];
  87320. if (!technique) {
  87321. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  87322. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  87323. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87324. onSuccess(defaultMaterial);
  87325. return;
  87326. }
  87327. var program = gltfRuntime.programs[technique.program];
  87328. var states = technique.states;
  87329. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  87330. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  87331. var newVertexShader = "";
  87332. var newPixelShader = "";
  87333. var vertexTokenizer = new Tokenizer(vertexShader);
  87334. var pixelTokenizer = new Tokenizer(pixelShader);
  87335. var unTreatedUniforms = {};
  87336. var uniforms = [];
  87337. var attributes = [];
  87338. var samplers = [];
  87339. // Fill uniform, sampler2D and attributes
  87340. for (var unif in technique.uniforms) {
  87341. var uniform = technique.uniforms[unif];
  87342. var uniformParameter = technique.parameters[uniform];
  87343. unTreatedUniforms[unif] = uniformParameter;
  87344. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  87345. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  87346. if (transformIndex !== -1) {
  87347. uniforms.push(babylonTransforms[transformIndex]);
  87348. delete unTreatedUniforms[unif];
  87349. }
  87350. else {
  87351. uniforms.push(unif);
  87352. }
  87353. }
  87354. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  87355. samplers.push(unif);
  87356. }
  87357. else {
  87358. uniforms.push(unif);
  87359. }
  87360. }
  87361. for (var attr in technique.attributes) {
  87362. var attribute = technique.attributes[attr];
  87363. var attributeParameter = technique.parameters[attribute];
  87364. if (attributeParameter.semantic) {
  87365. attributes.push(getAttribute(attributeParameter));
  87366. }
  87367. }
  87368. // Configure vertex shader
  87369. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  87370. var tokenType = vertexTokenizer.currentToken;
  87371. if (tokenType !== ETokenType.IDENTIFIER) {
  87372. newVertexShader += vertexTokenizer.currentString;
  87373. continue;
  87374. }
  87375. var foundAttribute = false;
  87376. for (var attr in technique.attributes) {
  87377. var attribute = technique.attributes[attr];
  87378. var attributeParameter = technique.parameters[attribute];
  87379. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  87380. newVertexShader += getAttribute(attributeParameter);
  87381. foundAttribute = true;
  87382. break;
  87383. }
  87384. }
  87385. if (foundAttribute) {
  87386. continue;
  87387. }
  87388. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  87389. }
  87390. // Configure pixel shader
  87391. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  87392. var tokenType = pixelTokenizer.currentToken;
  87393. if (tokenType !== ETokenType.IDENTIFIER) {
  87394. newPixelShader += pixelTokenizer.currentString;
  87395. continue;
  87396. }
  87397. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  87398. }
  87399. // Create shader material
  87400. var shaderPath = {
  87401. vertex: program.vertexShader + id,
  87402. fragment: program.fragmentShader + id
  87403. };
  87404. var options = {
  87405. attributes: attributes,
  87406. uniforms: uniforms,
  87407. samplers: samplers,
  87408. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  87409. };
  87410. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  87411. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  87412. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  87413. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  87414. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  87415. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87416. if (states && states.functions) {
  87417. var functions = states.functions;
  87418. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  87419. shaderMaterial.backFaceCulling = false;
  87420. }
  87421. var blendFunc = functions.blendFuncSeparate;
  87422. if (blendFunc) {
  87423. 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) {
  87424. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  87425. }
  87426. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87427. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87428. }
  87429. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87430. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  87431. }
  87432. 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) {
  87433. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  87434. }
  87435. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87436. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  87437. }
  87438. 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) {
  87439. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  87440. }
  87441. }
  87442. }
  87443. };
  87444. return GLTFLoaderBase;
  87445. }());
  87446. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  87447. /**
  87448. * glTF V1 Loader
  87449. */
  87450. var GLTFLoader = /** @class */ (function () {
  87451. function GLTFLoader() {
  87452. // #region Stubs for IGLTFLoader interface
  87453. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87454. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87455. this.compileMaterials = false;
  87456. this.useClipPlane = false;
  87457. this.compileShadowGenerators = false;
  87458. this.onDisposeObservable = new BABYLON.Observable();
  87459. this.onMeshLoadedObservable = new BABYLON.Observable();
  87460. this.onTextureLoadedObservable = new BABYLON.Observable();
  87461. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87462. this.onCompleteObservable = new BABYLON.Observable();
  87463. }
  87464. GLTFLoader.RegisterExtension = function (extension) {
  87465. if (GLTFLoader.Extensions[extension.name]) {
  87466. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  87467. return;
  87468. }
  87469. GLTFLoader.Extensions[extension.name] = extension;
  87470. };
  87471. GLTFLoader.prototype.dispose = function () { };
  87472. // #endregion
  87473. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87474. var _this = this;
  87475. scene.useRightHandedSystem = true;
  87476. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87477. gltfRuntime.importOnlyMeshes = true;
  87478. if (meshesNames === "") {
  87479. gltfRuntime.importMeshesNames = [];
  87480. }
  87481. else if (typeof meshesNames === "string") {
  87482. gltfRuntime.importMeshesNames = [meshesNames];
  87483. }
  87484. else if (meshesNames && !(meshesNames instanceof Array)) {
  87485. gltfRuntime.importMeshesNames = [meshesNames];
  87486. }
  87487. else {
  87488. gltfRuntime.importMeshesNames = [];
  87489. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  87490. }
  87491. // Create nodes
  87492. _this._createNodes(gltfRuntime);
  87493. var meshes = new Array();
  87494. var skeletons = new Array();
  87495. // Fill arrays of meshes and skeletons
  87496. for (var nde in gltfRuntime.nodes) {
  87497. var node = gltfRuntime.nodes[nde];
  87498. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  87499. meshes.push(node.babylonNode);
  87500. }
  87501. }
  87502. for (var skl in gltfRuntime.skins) {
  87503. var skin = gltfRuntime.skins[skl];
  87504. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  87505. skeletons.push(skin.babylonSkeleton);
  87506. }
  87507. }
  87508. // Load buffers, shaders, materials, etc.
  87509. _this._loadBuffersAsync(gltfRuntime, function () {
  87510. _this._loadShadersAsync(gltfRuntime, function () {
  87511. importMaterials(gltfRuntime);
  87512. postLoad(gltfRuntime);
  87513. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87514. onSuccess(meshes, [], skeletons);
  87515. }
  87516. });
  87517. }, onProgress);
  87518. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87519. onSuccess(meshes, [], skeletons);
  87520. }
  87521. }, onError);
  87522. return true;
  87523. };
  87524. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87525. var _this = this;
  87526. scene.useRightHandedSystem = true;
  87527. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87528. // Load runtime extensios
  87529. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  87530. // Create nodes
  87531. _this._createNodes(gltfRuntime);
  87532. // Load buffers, shaders, materials, etc.
  87533. _this._loadBuffersAsync(gltfRuntime, function () {
  87534. _this._loadShadersAsync(gltfRuntime, function () {
  87535. importMaterials(gltfRuntime);
  87536. postLoad(gltfRuntime);
  87537. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  87538. onSuccess();
  87539. }
  87540. });
  87541. });
  87542. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  87543. onSuccess();
  87544. }
  87545. }, onError);
  87546. }, onError);
  87547. };
  87548. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  87549. var hasShaders = false;
  87550. var processShader = function (sha, shader) {
  87551. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  87552. gltfRuntime.loadedShaderCount++;
  87553. if (shaderString) {
  87554. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  87555. }
  87556. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  87557. onload();
  87558. }
  87559. }, function () {
  87560. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  87561. });
  87562. };
  87563. for (var sha in gltfRuntime.shaders) {
  87564. hasShaders = true;
  87565. var shader = gltfRuntime.shaders[sha];
  87566. if (shader) {
  87567. processShader.bind(this, sha, shader)();
  87568. }
  87569. else {
  87570. BABYLON.Tools.Error("No shader named: " + sha);
  87571. }
  87572. }
  87573. if (!hasShaders) {
  87574. onload();
  87575. }
  87576. };
  87577. ;
  87578. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  87579. var hasBuffers = false;
  87580. var processBuffer = function (buf, buffer) {
  87581. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  87582. gltfRuntime.loadedBufferCount++;
  87583. if (bufferView) {
  87584. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  87585. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  87586. }
  87587. gltfRuntime.loadedBufferViews[buf] = bufferView;
  87588. }
  87589. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  87590. onLoad();
  87591. }
  87592. }, function () {
  87593. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  87594. });
  87595. };
  87596. for (var buf in gltfRuntime.buffers) {
  87597. hasBuffers = true;
  87598. var buffer = gltfRuntime.buffers[buf];
  87599. if (buffer) {
  87600. processBuffer.bind(this, buf, buffer)();
  87601. }
  87602. else {
  87603. BABYLON.Tools.Error("No buffer named: " + buf);
  87604. }
  87605. }
  87606. if (!hasBuffers) {
  87607. onLoad();
  87608. }
  87609. };
  87610. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  87611. var currentScene = gltfRuntime.currentScene;
  87612. if (currentScene) {
  87613. // Only one scene even if multiple scenes are defined
  87614. for (var i = 0; i < currentScene.nodes.length; i++) {
  87615. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87616. }
  87617. }
  87618. else {
  87619. // Load all scenes
  87620. for (var thing in gltfRuntime.scenes) {
  87621. currentScene = gltfRuntime.scenes[thing];
  87622. for (var i = 0; i < currentScene.nodes.length; i++) {
  87623. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87624. }
  87625. }
  87626. }
  87627. };
  87628. GLTFLoader.Extensions = {};
  87629. return GLTFLoader;
  87630. }());
  87631. GLTF1.GLTFLoader = GLTFLoader;
  87632. ;
  87633. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  87634. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87635. })(BABYLON || (BABYLON = {}));
  87636. //# sourceMappingURL=babylon.glTFLoader.js.map
  87637. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87638. var BABYLON;
  87639. (function (BABYLON) {
  87640. var GLTF1;
  87641. (function (GLTF1) {
  87642. /**
  87643. * Utils functions for GLTF
  87644. */
  87645. var GLTFUtils = /** @class */ (function () {
  87646. function GLTFUtils() {
  87647. }
  87648. /**
  87649. * Sets the given "parameter" matrix
  87650. * @param scene: the {BABYLON.Scene} object
  87651. * @param source: the source node where to pick the matrix
  87652. * @param parameter: the GLTF technique parameter
  87653. * @param uniformName: the name of the shader's uniform
  87654. * @param shaderMaterial: the shader material
  87655. */
  87656. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  87657. var mat = null;
  87658. if (parameter.semantic === "MODEL") {
  87659. mat = source.getWorldMatrix();
  87660. }
  87661. else if (parameter.semantic === "PROJECTION") {
  87662. mat = scene.getProjectionMatrix();
  87663. }
  87664. else if (parameter.semantic === "VIEW") {
  87665. mat = scene.getViewMatrix();
  87666. }
  87667. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  87668. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  87669. }
  87670. else if (parameter.semantic === "MODELVIEW") {
  87671. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  87672. }
  87673. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  87674. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  87675. }
  87676. else if (parameter.semantic === "MODELINVERSE") {
  87677. mat = source.getWorldMatrix().invert();
  87678. }
  87679. else if (parameter.semantic === "VIEWINVERSE") {
  87680. mat = scene.getViewMatrix().invert();
  87681. }
  87682. else if (parameter.semantic === "PROJECTIONINVERSE") {
  87683. mat = scene.getProjectionMatrix().invert();
  87684. }
  87685. else if (parameter.semantic === "MODELVIEWINVERSE") {
  87686. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  87687. }
  87688. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  87689. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  87690. }
  87691. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  87692. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  87693. }
  87694. else {
  87695. debugger;
  87696. }
  87697. if (mat) {
  87698. switch (parameter.type) {
  87699. case GLTF1.EParameterType.FLOAT_MAT2:
  87700. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  87701. break;
  87702. case GLTF1.EParameterType.FLOAT_MAT3:
  87703. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  87704. break;
  87705. case GLTF1.EParameterType.FLOAT_MAT4:
  87706. shaderMaterial.setMatrix(uniformName, mat);
  87707. break;
  87708. default: break;
  87709. }
  87710. }
  87711. };
  87712. /**
  87713. * Sets the given "parameter" matrix
  87714. * @param shaderMaterial: the shader material
  87715. * @param uniform: the name of the shader's uniform
  87716. * @param value: the value of the uniform
  87717. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  87718. */
  87719. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  87720. switch (type) {
  87721. case GLTF1.EParameterType.FLOAT:
  87722. shaderMaterial.setFloat(uniform, value);
  87723. return true;
  87724. case GLTF1.EParameterType.FLOAT_VEC2:
  87725. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  87726. return true;
  87727. case GLTF1.EParameterType.FLOAT_VEC3:
  87728. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  87729. return true;
  87730. case GLTF1.EParameterType.FLOAT_VEC4:
  87731. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  87732. return true;
  87733. default: return false;
  87734. }
  87735. };
  87736. /**
  87737. * If the uri is a base64 string
  87738. * @param uri: the uri to test
  87739. */
  87740. GLTFUtils.IsBase64 = function (uri) {
  87741. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  87742. };
  87743. /**
  87744. * Decode the base64 uri
  87745. * @param uri: the uri to decode
  87746. */
  87747. GLTFUtils.DecodeBase64 = function (uri) {
  87748. var decodedString = atob(uri.split(",")[1]);
  87749. var bufferLength = decodedString.length;
  87750. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  87751. for (var i = 0; i < bufferLength; i++) {
  87752. bufferView[i] = decodedString.charCodeAt(i);
  87753. }
  87754. return bufferView.buffer;
  87755. };
  87756. /**
  87757. * Returns the wrap mode of the texture
  87758. * @param mode: the mode value
  87759. */
  87760. GLTFUtils.GetWrapMode = function (mode) {
  87761. switch (mode) {
  87762. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  87763. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  87764. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87765. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87766. }
  87767. };
  87768. /**
  87769. * Returns the byte stride giving an accessor
  87770. * @param accessor: the GLTF accessor objet
  87771. */
  87772. GLTFUtils.GetByteStrideFromType = function (accessor) {
  87773. // Needs this function since "byteStride" isn't requiered in glTF format
  87774. var type = accessor.type;
  87775. switch (type) {
  87776. case "VEC2": return 2;
  87777. case "VEC3": return 3;
  87778. case "VEC4": return 4;
  87779. case "MAT2": return 4;
  87780. case "MAT3": return 9;
  87781. case "MAT4": return 16;
  87782. default: return 1;
  87783. }
  87784. };
  87785. /**
  87786. * Returns the texture filter mode giving a mode value
  87787. * @param mode: the filter mode value
  87788. */
  87789. GLTFUtils.GetTextureFilterMode = function (mode) {
  87790. switch (mode) {
  87791. case GLTF1.ETextureFilterType.LINEAR:
  87792. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  87793. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87794. case GLTF1.ETextureFilterType.NEAREST:
  87795. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  87796. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  87797. }
  87798. };
  87799. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  87800. var byteOffset = bufferView.byteOffset + byteOffset;
  87801. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  87802. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  87803. throw new Error("Buffer access is out of range");
  87804. }
  87805. var buffer = loadedBufferView.buffer;
  87806. byteOffset += loadedBufferView.byteOffset;
  87807. switch (componentType) {
  87808. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  87809. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  87810. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  87811. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  87812. default: return new Float32Array(buffer, byteOffset, byteLength);
  87813. }
  87814. };
  87815. /**
  87816. * Returns a buffer from its accessor
  87817. * @param gltfRuntime: the GLTF runtime
  87818. * @param accessor: the GLTF accessor
  87819. */
  87820. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  87821. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  87822. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  87823. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  87824. };
  87825. /**
  87826. * Decodes a buffer view into a string
  87827. * @param view: the buffer view
  87828. */
  87829. GLTFUtils.DecodeBufferToText = function (view) {
  87830. var result = "";
  87831. var length = view.byteLength;
  87832. for (var i = 0; i < length; ++i) {
  87833. result += String.fromCharCode(view[i]);
  87834. }
  87835. return result;
  87836. };
  87837. /**
  87838. * Returns the default material of gltf. Related to
  87839. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  87840. * @param scene: the Babylon.js scene
  87841. */
  87842. GLTFUtils.GetDefaultMaterial = function (scene) {
  87843. if (!GLTFUtils._DefaultMaterial) {
  87844. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  87845. "precision highp float;",
  87846. "",
  87847. "uniform mat4 worldView;",
  87848. "uniform mat4 projection;",
  87849. "",
  87850. "attribute vec3 position;",
  87851. "",
  87852. "void main(void)",
  87853. "{",
  87854. " gl_Position = projection * worldView * vec4(position, 1.0);",
  87855. "}"
  87856. ].join("\n");
  87857. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  87858. "precision highp float;",
  87859. "",
  87860. "uniform vec4 u_emission;",
  87861. "",
  87862. "void main(void)",
  87863. "{",
  87864. " gl_FragColor = u_emission;",
  87865. "}"
  87866. ].join("\n");
  87867. var shaderPath = {
  87868. vertex: "GLTFDefaultMaterial",
  87869. fragment: "GLTFDefaultMaterial"
  87870. };
  87871. var options = {
  87872. attributes: ["position"],
  87873. uniforms: ["worldView", "projection", "u_emission"],
  87874. samplers: new Array(),
  87875. needAlphaBlending: false
  87876. };
  87877. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  87878. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  87879. }
  87880. return GLTFUtils._DefaultMaterial;
  87881. };
  87882. // The GLTF default material
  87883. GLTFUtils._DefaultMaterial = null;
  87884. return GLTFUtils;
  87885. }());
  87886. GLTF1.GLTFUtils = GLTFUtils;
  87887. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87888. })(BABYLON || (BABYLON = {}));
  87889. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  87890. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87891. var BABYLON;
  87892. (function (BABYLON) {
  87893. var GLTF1;
  87894. (function (GLTF1) {
  87895. var GLTFLoaderExtension = /** @class */ (function () {
  87896. function GLTFLoaderExtension(name) {
  87897. this._name = name;
  87898. }
  87899. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  87900. get: function () {
  87901. return this._name;
  87902. },
  87903. enumerable: true,
  87904. configurable: true
  87905. });
  87906. /**
  87907. * Defines an override for loading the runtime
  87908. * Return true to stop further extensions from loading the runtime
  87909. */
  87910. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87911. return false;
  87912. };
  87913. /**
  87914. * Defines an onverride for creating gltf runtime
  87915. * Return true to stop further extensions from creating the runtime
  87916. */
  87917. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87918. return false;
  87919. };
  87920. /**
  87921. * Defines an override for loading buffers
  87922. * Return true to stop further extensions from loading this buffer
  87923. */
  87924. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87925. return false;
  87926. };
  87927. /**
  87928. * Defines an override for loading texture buffers
  87929. * Return true to stop further extensions from loading this texture data
  87930. */
  87931. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87932. return false;
  87933. };
  87934. /**
  87935. * Defines an override for creating textures
  87936. * Return true to stop further extensions from loading this texture
  87937. */
  87938. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87939. return false;
  87940. };
  87941. /**
  87942. * Defines an override for loading shader strings
  87943. * Return true to stop further extensions from loading this shader data
  87944. */
  87945. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87946. return false;
  87947. };
  87948. /**
  87949. * Defines an override for loading materials
  87950. * Return true to stop further extensions from loading this material
  87951. */
  87952. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87953. return false;
  87954. };
  87955. // ---------
  87956. // Utilities
  87957. // ---------
  87958. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87959. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87960. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  87961. }, function () {
  87962. setTimeout(function () {
  87963. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87964. });
  87965. });
  87966. };
  87967. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87968. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87969. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  87970. }, function () {
  87971. setTimeout(function () {
  87972. onSuccess();
  87973. });
  87974. });
  87975. };
  87976. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87977. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87978. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87979. }, function () {
  87980. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87981. });
  87982. };
  87983. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  87984. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  87985. };
  87986. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87987. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87988. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87989. }, function () {
  87990. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87991. });
  87992. };
  87993. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87994. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87995. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87996. }, function () {
  87997. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87998. });
  87999. };
  88000. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88001. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  88002. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  88003. }, function () {
  88004. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  88005. });
  88006. };
  88007. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  88008. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  88009. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  88010. }, function () {
  88011. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  88012. });
  88013. };
  88014. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  88015. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  88016. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  88017. if (func(loaderExtension)) {
  88018. return;
  88019. }
  88020. }
  88021. defaultFunc();
  88022. };
  88023. return GLTFLoaderExtension;
  88024. }());
  88025. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  88026. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88027. })(BABYLON || (BABYLON = {}));
  88028. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  88029. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88030. var BABYLON;
  88031. (function (BABYLON) {
  88032. var GLTF1;
  88033. (function (GLTF1) {
  88034. var BinaryExtensionBufferName = "binary_glTF";
  88035. ;
  88036. ;
  88037. var GLTFBinaryExtension = /** @class */ (function (_super) {
  88038. __extends(GLTFBinaryExtension, _super);
  88039. function GLTFBinaryExtension() {
  88040. return _super.call(this, "KHR_binary_glTF") || this;
  88041. }
  88042. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  88043. var extensionsUsed = data.json.extensionsUsed;
  88044. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  88045. return false;
  88046. }
  88047. this._bin = data.bin;
  88048. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  88049. return true;
  88050. };
  88051. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88052. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  88053. return false;
  88054. }
  88055. if (id !== BinaryExtensionBufferName) {
  88056. return false;
  88057. }
  88058. onSuccess(this._bin);
  88059. return true;
  88060. };
  88061. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  88062. var texture = gltfRuntime.textures[id];
  88063. var source = gltfRuntime.images[texture.source];
  88064. if (!source.extensions || !(this.name in source.extensions)) {
  88065. return false;
  88066. }
  88067. var sourceExt = source.extensions[this.name];
  88068. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  88069. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  88070. onSuccess(buffer);
  88071. return true;
  88072. };
  88073. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  88074. var shader = gltfRuntime.shaders[id];
  88075. if (!shader.extensions || !(this.name in shader.extensions)) {
  88076. return false;
  88077. }
  88078. var binaryExtensionShader = shader.extensions[this.name];
  88079. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  88080. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  88081. setTimeout(function () {
  88082. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  88083. onSuccess(shaderString);
  88084. });
  88085. return true;
  88086. };
  88087. return GLTFBinaryExtension;
  88088. }(GLTF1.GLTFLoaderExtension));
  88089. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  88090. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  88091. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88092. })(BABYLON || (BABYLON = {}));
  88093. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  88094. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88095. var BABYLON;
  88096. (function (BABYLON) {
  88097. var GLTF1;
  88098. (function (GLTF1) {
  88099. ;
  88100. ;
  88101. ;
  88102. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  88103. __extends(GLTFMaterialsCommonExtension, _super);
  88104. function GLTFMaterialsCommonExtension() {
  88105. return _super.call(this, "KHR_materials_common") || this;
  88106. }
  88107. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  88108. if (!gltfRuntime.extensions)
  88109. return false;
  88110. var extension = gltfRuntime.extensions[this.name];
  88111. if (!extension)
  88112. return false;
  88113. // Create lights
  88114. var lights = extension.lights;
  88115. if (lights) {
  88116. for (var thing in lights) {
  88117. var light = lights[thing];
  88118. switch (light.type) {
  88119. case "ambient":
  88120. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  88121. var ambient = light.ambient;
  88122. if (ambient) {
  88123. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  88124. }
  88125. break;
  88126. case "point":
  88127. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  88128. var point = light.point;
  88129. if (point) {
  88130. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  88131. }
  88132. break;
  88133. case "directional":
  88134. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  88135. var directional = light.directional;
  88136. if (directional) {
  88137. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  88138. }
  88139. break;
  88140. case "spot":
  88141. var spot = light.spot;
  88142. if (spot) {
  88143. 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);
  88144. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  88145. }
  88146. break;
  88147. default:
  88148. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  88149. break;
  88150. }
  88151. }
  88152. }
  88153. return false;
  88154. };
  88155. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  88156. var material = gltfRuntime.materials[id];
  88157. if (!material || !material.extensions)
  88158. return false;
  88159. var extension = material.extensions[this.name];
  88160. if (!extension)
  88161. return false;
  88162. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  88163. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  88164. if (extension.technique === "CONSTANT") {
  88165. standardMaterial.disableLighting = true;
  88166. }
  88167. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  88168. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  88169. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  88170. // Ambient
  88171. if (typeof extension.values.ambient === "string") {
  88172. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  88173. }
  88174. else {
  88175. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  88176. }
  88177. // Diffuse
  88178. if (typeof extension.values.diffuse === "string") {
  88179. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  88180. }
  88181. else {
  88182. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  88183. }
  88184. // Emission
  88185. if (typeof extension.values.emission === "string") {
  88186. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  88187. }
  88188. else {
  88189. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  88190. }
  88191. // Specular
  88192. if (typeof extension.values.specular === "string") {
  88193. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  88194. }
  88195. else {
  88196. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  88197. }
  88198. return true;
  88199. };
  88200. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  88201. // Create buffer from texture url
  88202. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  88203. // Create texture from buffer
  88204. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  88205. }, onError);
  88206. };
  88207. return GLTFMaterialsCommonExtension;
  88208. }(GLTF1.GLTFLoaderExtension));
  88209. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  88210. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  88211. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88212. })(BABYLON || (BABYLON = {}));
  88213. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  88214. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88215. var BABYLON;
  88216. (function (BABYLON) {
  88217. var GLTF2;
  88218. (function (GLTF2) {
  88219. /**
  88220. * Enums
  88221. */
  88222. var EComponentType;
  88223. (function (EComponentType) {
  88224. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88225. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88226. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88227. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88228. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88229. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88230. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  88231. var EMeshPrimitiveMode;
  88232. (function (EMeshPrimitiveMode) {
  88233. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  88234. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  88235. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  88236. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  88237. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  88238. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  88239. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  88240. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  88241. var ETextureMagFilter;
  88242. (function (ETextureMagFilter) {
  88243. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  88244. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  88245. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  88246. var ETextureMinFilter;
  88247. (function (ETextureMinFilter) {
  88248. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  88249. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  88250. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88251. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88252. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88253. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88254. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  88255. var ETextureWrapMode;
  88256. (function (ETextureWrapMode) {
  88257. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88258. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88259. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88260. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  88261. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88262. })(BABYLON || (BABYLON = {}));
  88263. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88264. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88265. var BABYLON;
  88266. (function (BABYLON) {
  88267. var GLTF2;
  88268. (function (GLTF2) {
  88269. var GLTFLoaderTracker = /** @class */ (function () {
  88270. function GLTFLoaderTracker(onComplete) {
  88271. this._pendingCount = 0;
  88272. this._callback = onComplete;
  88273. }
  88274. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  88275. this._pendingCount++;
  88276. };
  88277. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  88278. if (--this._pendingCount === 0) {
  88279. this._callback();
  88280. }
  88281. };
  88282. return GLTFLoaderTracker;
  88283. }());
  88284. var GLTFLoader = /** @class */ (function () {
  88285. function GLTFLoader() {
  88286. this._disposed = false;
  88287. this._defaultSampler = {};
  88288. this._renderReady = false;
  88289. this._requests = new Array();
  88290. this._renderReadyObservable = new BABYLON.Observable();
  88291. // Count of pending work that needs to complete before the asset is rendered.
  88292. this._renderPendingCount = 0;
  88293. // Count of pending work that needs to complete before the loader is disposed.
  88294. this._loaderPendingCount = 0;
  88295. this._loaderTrackers = new Array();
  88296. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  88297. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  88298. this.compileMaterials = false;
  88299. this.useClipPlane = false;
  88300. this.compileShadowGenerators = false;
  88301. this.onDisposeObservable = new BABYLON.Observable();
  88302. this.onMeshLoadedObservable = new BABYLON.Observable();
  88303. this.onTextureLoadedObservable = new BABYLON.Observable();
  88304. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88305. this.onCompleteObservable = new BABYLON.Observable();
  88306. }
  88307. GLTFLoader.RegisterExtension = function (extension) {
  88308. if (GLTFLoader.Extensions[extension.name]) {
  88309. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  88310. return;
  88311. }
  88312. GLTFLoader.Extensions[extension.name] = extension;
  88313. // Keep the order of registration so that extensions registered first are called first.
  88314. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  88315. };
  88316. GLTFLoader.prototype.dispose = function () {
  88317. if (this._disposed) {
  88318. return;
  88319. }
  88320. this._disposed = true;
  88321. this._abortRequests();
  88322. this._releaseResources();
  88323. this.onDisposeObservable.notifyObservers(this);
  88324. };
  88325. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  88326. var _this = this;
  88327. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  88328. if (onSuccess) {
  88329. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  88330. }
  88331. }, onProgress, onError);
  88332. };
  88333. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  88334. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  88335. };
  88336. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  88337. var _this = this;
  88338. this._babylonScene = scene;
  88339. this._rootUrl = rootUrl;
  88340. this._successCallback = onSuccess;
  88341. this._progressCallback = onProgress;
  88342. this._errorCallback = onError;
  88343. this._tryCatchOnError(function () {
  88344. _this._loadData(data);
  88345. _this._addPendingData(_this);
  88346. _this._loadDefaultScene(nodeNames);
  88347. _this._loadAnimations();
  88348. _this._removePendingData(_this);
  88349. });
  88350. };
  88351. GLTFLoader.prototype._onProgress = function () {
  88352. if (!this._progressCallback) {
  88353. return;
  88354. }
  88355. var lengthComputable = true;
  88356. var loaded = 0;
  88357. var total = 0;
  88358. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  88359. var request = _a[_i];
  88360. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  88361. return;
  88362. }
  88363. lengthComputable = lengthComputable && request._lengthComputable;
  88364. loaded += request._loaded;
  88365. total += request._total;
  88366. }
  88367. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  88368. };
  88369. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  88370. if (this._renderReady) {
  88371. func();
  88372. }
  88373. else {
  88374. this._renderReadyObservable.add(func);
  88375. }
  88376. };
  88377. GLTFLoader.prototype._onRenderReady = function () {
  88378. this._rootNode.babylonMesh.setEnabled(true);
  88379. this._startAnimations();
  88380. if (this._successCallback) {
  88381. this._successCallback();
  88382. }
  88383. this._renderReadyObservable.notifyObservers(this);
  88384. };
  88385. GLTFLoader.prototype._onComplete = function () {
  88386. this._abortRequests();
  88387. this._releaseResources();
  88388. this.onCompleteObservable.notifyObservers(this);
  88389. };
  88390. GLTFLoader.prototype._loadData = function (data) {
  88391. this._gltf = data.json;
  88392. // Assign the index of each object for convinience.
  88393. GLTFLoader._AssignIndices(this._gltf.accessors);
  88394. GLTFLoader._AssignIndices(this._gltf.animations);
  88395. GLTFLoader._AssignIndices(this._gltf.buffers);
  88396. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  88397. GLTFLoader._AssignIndices(this._gltf.images);
  88398. GLTFLoader._AssignIndices(this._gltf.materials);
  88399. GLTFLoader._AssignIndices(this._gltf.meshes);
  88400. GLTFLoader._AssignIndices(this._gltf.nodes);
  88401. GLTFLoader._AssignIndices(this._gltf.samplers);
  88402. GLTFLoader._AssignIndices(this._gltf.scenes);
  88403. GLTFLoader._AssignIndices(this._gltf.skins);
  88404. GLTFLoader._AssignIndices(this._gltf.textures);
  88405. // Handle global extensions as they may add their own data types.
  88406. GLTF2.GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  88407. if (data.bin) {
  88408. var buffers = this._gltf.buffers;
  88409. if (buffers && buffers[0] && !buffers[0].uri) {
  88410. var binaryBuffer = buffers[0];
  88411. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  88412. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  88413. }
  88414. binaryBuffer.loadedData = data.bin;
  88415. }
  88416. else {
  88417. BABYLON.Tools.Warn("Unexpected BIN chunk");
  88418. }
  88419. }
  88420. };
  88421. GLTFLoader.prototype._getMeshes = function () {
  88422. var meshes = new Array();
  88423. // Root mesh is always first.
  88424. meshes.push(this._rootNode.babylonMesh);
  88425. var nodes = this._gltf.nodes;
  88426. if (nodes) {
  88427. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  88428. var node = nodes_1[_i];
  88429. if (node.babylonMesh) {
  88430. meshes.push(node.babylonMesh);
  88431. }
  88432. }
  88433. }
  88434. return meshes;
  88435. };
  88436. GLTFLoader.prototype._getSkeletons = function () {
  88437. var skeletons = new Array();
  88438. var skins = this._gltf.skins;
  88439. if (skins) {
  88440. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  88441. var skin = skins_1[_i];
  88442. if (skin.babylonSkeleton) {
  88443. skeletons.push(skin.babylonSkeleton);
  88444. }
  88445. }
  88446. }
  88447. return skeletons;
  88448. };
  88449. GLTFLoader.prototype._startAnimations = function () {
  88450. var animations = this._gltf.animations;
  88451. if (!animations) {
  88452. return;
  88453. }
  88454. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  88455. var animation = animations_1[_i];
  88456. animation.babylonAnimationGroup.normalize();
  88457. }
  88458. switch (this.animationStartMode) {
  88459. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  88460. // do nothing
  88461. break;
  88462. }
  88463. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  88464. var animation = animations[0];
  88465. animation.babylonAnimationGroup.start(true);
  88466. break;
  88467. }
  88468. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  88469. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  88470. var animation = animations_2[_a];
  88471. animation.babylonAnimationGroup.start(true);
  88472. }
  88473. break;
  88474. }
  88475. default: {
  88476. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  88477. return;
  88478. }
  88479. }
  88480. };
  88481. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  88482. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  88483. if (!scene) {
  88484. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  88485. }
  88486. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  88487. };
  88488. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  88489. var _this = this;
  88490. GLTF2.GLTFLoaderExtension.LoadScene(this, context, scene);
  88491. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  88492. switch (this.coordinateSystemMode) {
  88493. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  88494. if (!this._babylonScene.useRightHandedSystem) {
  88495. this._rootNode.rotation = [0, 1, 0, 0];
  88496. this._rootNode.scale = [1, 1, -1];
  88497. this._loadTransform(this._rootNode);
  88498. }
  88499. break;
  88500. }
  88501. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  88502. this._babylonScene.useRightHandedSystem = true;
  88503. break;
  88504. }
  88505. default: {
  88506. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  88507. return;
  88508. }
  88509. }
  88510. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  88511. var nodeIndices = scene.nodes;
  88512. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  88513. node.parent = parentNode;
  88514. return true;
  88515. }, this._rootNode);
  88516. if (nodeNames) {
  88517. if (!(nodeNames instanceof Array)) {
  88518. nodeNames = [nodeNames];
  88519. }
  88520. var filteredNodeIndices_1 = new Array();
  88521. this._traverseNodes(context, nodeIndices, function (node) {
  88522. if (nodeNames.indexOf(node.name) !== -1) {
  88523. filteredNodeIndices_1.push(node.index);
  88524. node.parent = _this._rootNode;
  88525. return false;
  88526. }
  88527. return true;
  88528. }, this._rootNode);
  88529. nodeIndices = filteredNodeIndices_1;
  88530. }
  88531. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  88532. var index = nodeIndices_1[_i];
  88533. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88534. if (!node) {
  88535. throw new Error(context + ": Failed to find node " + index);
  88536. }
  88537. this._loadNode("#/nodes/" + index, node);
  88538. }
  88539. // Disable the root mesh until the asset is ready to render.
  88540. this._rootNode.babylonMesh.setEnabled(false);
  88541. };
  88542. GLTFLoader.prototype._loadNode = function (context, node) {
  88543. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  88544. return;
  88545. }
  88546. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  88547. this._loadTransform(node);
  88548. if (node.mesh != null) {
  88549. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  88550. if (!mesh) {
  88551. throw new Error(context + ": Failed to find mesh " + node.mesh);
  88552. }
  88553. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  88554. }
  88555. node.babylonMesh.parent = node.parent.babylonMesh;
  88556. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88557. node.babylonAnimationTargets.push(node.babylonMesh);
  88558. if (node.skin != null) {
  88559. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  88560. if (!skin_1) {
  88561. throw new Error(context + ": Failed to find skin " + node.skin);
  88562. }
  88563. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  88564. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  88565. node.babylonMesh._refreshBoundingInfo(true);
  88566. });
  88567. node.babylonMesh.parent = this._rootNode.babylonMesh;
  88568. node.babylonMesh.position = BABYLON.Vector3.Zero();
  88569. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88570. node.babylonMesh.scaling = BABYLON.Vector3.One();
  88571. }
  88572. if (node.camera != null) {
  88573. // TODO: handle cameras
  88574. }
  88575. if (node.children) {
  88576. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  88577. var index = _a[_i];
  88578. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88579. if (!childNode) {
  88580. throw new Error(context + ": Failed to find child node " + index);
  88581. }
  88582. this._loadNode("#/nodes/" + index, childNode);
  88583. }
  88584. }
  88585. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  88586. };
  88587. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  88588. var _this = this;
  88589. var primitives = mesh.primitives;
  88590. if (!primitives || primitives.length === 0) {
  88591. throw new Error(context + ": Primitives are missing");
  88592. }
  88593. this._createMorphTargets(context, node, mesh);
  88594. this._loadAllVertexDataAsync(context, mesh, function () {
  88595. _this._loadMorphTargets(context, node, mesh);
  88596. var vertexData = new BABYLON.VertexData();
  88597. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  88598. var primitive = primitives_1[_i];
  88599. vertexData.merge(primitive.vertexData);
  88600. }
  88601. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  88602. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  88603. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  88604. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  88605. node.babylonMesh.subMeshes = [];
  88606. var verticesStart = 0;
  88607. var indicesStart = 0;
  88608. for (var index = 0; index < primitives.length; index++) {
  88609. var vertexData_1 = primitives[index].vertexData;
  88610. var verticesCount = vertexData_1.positions.length;
  88611. var indicesCount = vertexData_1.indices.length;
  88612. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  88613. verticesStart += verticesCount;
  88614. indicesStart += indicesCount;
  88615. }
  88616. ;
  88617. });
  88618. if (primitives.length === 1) {
  88619. var primitive = primitives[0];
  88620. if (primitive.material == null) {
  88621. node.babylonMesh.material = this._getDefaultMaterial();
  88622. }
  88623. else {
  88624. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  88625. if (!material) {
  88626. throw new Error(context + ": Failed to find material " + primitive.material);
  88627. }
  88628. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88629. if (isNew) {
  88630. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88631. }
  88632. node.babylonMesh.material = babylonMaterial;
  88633. });
  88634. }
  88635. }
  88636. else {
  88637. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  88638. node.babylonMesh.material = multiMaterial;
  88639. var subMaterials_1 = multiMaterial.subMaterials;
  88640. var _loop_1 = function (index) {
  88641. var primitive = primitives[index];
  88642. if (primitive.material == null) {
  88643. subMaterials_1[index] = this_1._getDefaultMaterial();
  88644. }
  88645. else {
  88646. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  88647. if (!material) {
  88648. throw new Error(context + ": Failed to find material " + primitive.material);
  88649. }
  88650. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88651. if (isNew) {
  88652. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88653. }
  88654. subMaterials_1[index] = babylonMaterial;
  88655. });
  88656. }
  88657. };
  88658. var this_1 = this;
  88659. for (var index = 0; index < primitives.length; index++) {
  88660. _loop_1(index);
  88661. }
  88662. ;
  88663. }
  88664. };
  88665. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  88666. var primitives = mesh.primitives;
  88667. var numRemainingPrimitives = primitives.length;
  88668. var _loop_2 = function (index) {
  88669. var primitive = primitives[index];
  88670. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  88671. primitive.vertexData = vertexData;
  88672. if (--numRemainingPrimitives === 0) {
  88673. onSuccess();
  88674. }
  88675. });
  88676. };
  88677. var this_2 = this;
  88678. for (var index = 0; index < primitives.length; index++) {
  88679. _loop_2(index);
  88680. }
  88681. };
  88682. /**
  88683. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  88684. * @param {ArrayBufferView} data
  88685. * @param {IGLTFAccessor} accessor
  88686. */
  88687. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  88688. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  88689. return data;
  88690. }
  88691. var buffer = data;
  88692. var factor = 1;
  88693. switch (accessor.componentType) {
  88694. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88695. factor = 1 / 255;
  88696. break;
  88697. }
  88698. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88699. factor = 1 / 65535;
  88700. break;
  88701. }
  88702. default: {
  88703. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88704. }
  88705. }
  88706. var result = new Float32Array(accessor.count * 2);
  88707. for (var i = 0; i < result.length; ++i) {
  88708. result[i] = buffer[i] * factor;
  88709. }
  88710. return result;
  88711. };
  88712. /**
  88713. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  88714. * @param {ArrayBufferView} data
  88715. * @param {IGLTFAccessor} accessor
  88716. */
  88717. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  88718. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  88719. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  88720. return data;
  88721. }
  88722. var buffer = data;
  88723. var factor = 1;
  88724. switch (accessor.componentType) {
  88725. case GLTF2.EComponentType.FLOAT: {
  88726. factor = 1;
  88727. break;
  88728. }
  88729. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88730. factor = 1 / 255;
  88731. break;
  88732. }
  88733. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88734. factor = 1 / 65535;
  88735. break;
  88736. }
  88737. default: {
  88738. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88739. }
  88740. }
  88741. var result = new Float32Array(accessor.count * 4);
  88742. if (colorComponentCount === 4) {
  88743. for (var i = 0; i < result.length; ++i) {
  88744. result[i] = buffer[i] * factor;
  88745. }
  88746. }
  88747. else {
  88748. var offset = 0;
  88749. for (var i = 0; i < result.length; ++i) {
  88750. if ((i + 1) % 4 === 0) {
  88751. result[i] = 1;
  88752. }
  88753. else {
  88754. result[i] = buffer[offset++] * factor;
  88755. }
  88756. }
  88757. }
  88758. return result;
  88759. };
  88760. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  88761. var _this = this;
  88762. var attributes = primitive.attributes;
  88763. if (!attributes) {
  88764. throw new Error(context + ": Attributes are missing");
  88765. }
  88766. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  88767. // TODO: handle other primitive modes
  88768. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  88769. }
  88770. var vertexData = new BABYLON.VertexData();
  88771. var numRemainingAttributes = Object.keys(attributes).length;
  88772. var _loop_3 = function (attribute) {
  88773. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  88774. if (!accessor) {
  88775. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88776. }
  88777. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88778. switch (attribute) {
  88779. case "POSITION": {
  88780. vertexData.positions = data;
  88781. break;
  88782. }
  88783. case "NORMAL": {
  88784. vertexData.normals = data;
  88785. break;
  88786. }
  88787. case "TANGENT": {
  88788. vertexData.tangents = data;
  88789. break;
  88790. }
  88791. case "TEXCOORD_0": {
  88792. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88793. break;
  88794. }
  88795. case "TEXCOORD_1": {
  88796. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88797. break;
  88798. }
  88799. case "JOINTS_0": {
  88800. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  88801. break;
  88802. }
  88803. case "WEIGHTS_0": {
  88804. //TODO: need to add support for normalized weights.
  88805. vertexData.matricesWeights = data;
  88806. break;
  88807. }
  88808. case "COLOR_0": {
  88809. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  88810. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  88811. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  88812. mesh.hasVertexAlpha = hasVertexAlpha;
  88813. }
  88814. break;
  88815. }
  88816. default: {
  88817. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88818. break;
  88819. }
  88820. }
  88821. if (--numRemainingAttributes === 0) {
  88822. if (primitive.indices == null) {
  88823. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  88824. for (var i = 0; i < vertexData.indices.length; i++) {
  88825. vertexData.indices[i] = i;
  88826. }
  88827. onSuccess(vertexData);
  88828. }
  88829. else {
  88830. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  88831. if (!indicesAccessor) {
  88832. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  88833. }
  88834. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  88835. vertexData.indices = data;
  88836. onSuccess(vertexData);
  88837. });
  88838. }
  88839. }
  88840. });
  88841. };
  88842. var this_3 = this;
  88843. for (var attribute in attributes) {
  88844. _loop_3(attribute);
  88845. }
  88846. };
  88847. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  88848. var primitives = mesh.primitives;
  88849. var targets = primitives[0].targets;
  88850. if (!targets) {
  88851. return;
  88852. }
  88853. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  88854. var primitive = primitives_2[_i];
  88855. if (!primitive.targets || primitive.targets.length != targets.length) {
  88856. throw new Error(context + ": All primitives are required to list the same number of targets");
  88857. }
  88858. }
  88859. var morphTargetManager = new BABYLON.MorphTargetManager();
  88860. node.babylonMesh.morphTargetManager = morphTargetManager;
  88861. for (var index = 0; index < targets.length; index++) {
  88862. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  88863. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  88864. }
  88865. };
  88866. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  88867. var morphTargetManager = node.babylonMesh.morphTargetManager;
  88868. if (!morphTargetManager) {
  88869. return;
  88870. }
  88871. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  88872. var numTargets = morphTargetManager.numTargets;
  88873. for (var index = 0; index < numTargets; index++) {
  88874. var vertexData = new BABYLON.VertexData();
  88875. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88876. var primitive = _a[_i];
  88877. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  88878. }
  88879. if (!vertexData.positions) {
  88880. throw new Error(context + ": Positions are missing");
  88881. }
  88882. var target = morphTargetManager.getTarget(index);
  88883. target.setPositions(vertexData.positions);
  88884. target.setNormals(vertexData.normals);
  88885. target.setTangents(vertexData.tangents);
  88886. }
  88887. });
  88888. };
  88889. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  88890. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  88891. var _loop_4 = function (primitive) {
  88892. var targets = primitive.targets;
  88893. primitive.targetsVertexData = new Array(targets.length);
  88894. var _loop_5 = function (index) {
  88895. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  88896. primitive.targetsVertexData[index] = vertexData;
  88897. if (--numRemainingTargets === 0) {
  88898. onSuccess();
  88899. }
  88900. });
  88901. };
  88902. for (var index = 0; index < targets.length; index++) {
  88903. _loop_5(index);
  88904. }
  88905. };
  88906. var this_4 = this;
  88907. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88908. var primitive = _a[_i];
  88909. _loop_4(primitive);
  88910. }
  88911. };
  88912. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  88913. var targetVertexData = new BABYLON.VertexData();
  88914. var numRemainingAttributes = Object.keys(attributes).length;
  88915. var _loop_6 = function (attribute) {
  88916. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  88917. if (!accessor) {
  88918. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88919. }
  88920. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88921. // glTF stores morph target information as deltas while babylon.js expects the final data.
  88922. // As a result we have to add the original data to the delta to calculate the final data.
  88923. var values = data;
  88924. switch (attribute) {
  88925. case "POSITION": {
  88926. for (var i = 0; i < values.length; i++) {
  88927. values[i] += vertexData.positions[i];
  88928. }
  88929. targetVertexData.positions = values;
  88930. break;
  88931. }
  88932. case "NORMAL": {
  88933. for (var i = 0; i < values.length; i++) {
  88934. values[i] += vertexData.normals[i];
  88935. }
  88936. targetVertexData.normals = values;
  88937. break;
  88938. }
  88939. case "TANGENT": {
  88940. // Tangent data for morph targets is stored as xyz delta.
  88941. // The vertexData.tangent is stored as xyzw.
  88942. // So we need to skip every fourth vertexData.tangent.
  88943. for (var i = 0, j = 0; i < values.length; i++, j++) {
  88944. values[i] += vertexData.tangents[j];
  88945. if ((i + 1) % 3 == 0) {
  88946. j++;
  88947. }
  88948. }
  88949. targetVertexData.tangents = values;
  88950. break;
  88951. }
  88952. default: {
  88953. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88954. break;
  88955. }
  88956. }
  88957. if (--numRemainingAttributes === 0) {
  88958. onSuccess(targetVertexData);
  88959. }
  88960. });
  88961. };
  88962. var this_5 = this;
  88963. for (var attribute in attributes) {
  88964. _loop_6(attribute);
  88965. }
  88966. };
  88967. GLTFLoader.prototype._loadTransform = function (node) {
  88968. var position = BABYLON.Vector3.Zero();
  88969. var rotation = BABYLON.Quaternion.Identity();
  88970. var scaling = BABYLON.Vector3.One();
  88971. if (node.matrix) {
  88972. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  88973. matrix.decompose(scaling, rotation, position);
  88974. }
  88975. else {
  88976. if (node.translation)
  88977. position = BABYLON.Vector3.FromArray(node.translation);
  88978. if (node.rotation)
  88979. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  88980. if (node.scale)
  88981. scaling = BABYLON.Vector3.FromArray(node.scale);
  88982. }
  88983. node.babylonMesh.position = position;
  88984. node.babylonMesh.rotationQuaternion = rotation;
  88985. node.babylonMesh.scaling = scaling;
  88986. };
  88987. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  88988. var _this = this;
  88989. if (skin.babylonSkeleton) {
  88990. onSuccess();
  88991. return;
  88992. }
  88993. var skeletonId = "skeleton" + skin.index;
  88994. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  88995. if (skin.inverseBindMatrices == null) {
  88996. this._loadBones(context, skin, null);
  88997. onSuccess();
  88998. }
  88999. else {
  89000. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  89001. if (!accessor) {
  89002. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  89003. }
  89004. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  89005. _this._loadBones(context, skin, data);
  89006. onSuccess();
  89007. });
  89008. }
  89009. };
  89010. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  89011. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  89012. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  89013. node.babylonAnimationTargets.push(babylonBone);
  89014. return babylonBone;
  89015. };
  89016. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  89017. var babylonBones = {};
  89018. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  89019. var index = _a[_i];
  89020. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89021. if (!node) {
  89022. throw new Error(context + ": Failed to find joint " + index);
  89023. }
  89024. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  89025. }
  89026. };
  89027. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  89028. var babylonBone = babylonBones[node.index];
  89029. if (babylonBone) {
  89030. return babylonBone;
  89031. }
  89032. var boneIndex = skin.joints.indexOf(node.index);
  89033. var baseMatrix = BABYLON.Matrix.Identity();
  89034. if (inverseBindMatrixData && boneIndex !== -1) {
  89035. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  89036. baseMatrix.invertToRef(baseMatrix);
  89037. }
  89038. var babylonParentBone = null;
  89039. if (node.parent !== this._rootNode) {
  89040. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  89041. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  89042. }
  89043. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  89044. babylonBones[node.index] = babylonBone;
  89045. return babylonBone;
  89046. };
  89047. GLTFLoader.prototype._getNodeMatrix = function (node) {
  89048. return node.matrix ?
  89049. BABYLON.Matrix.FromArray(node.matrix) :
  89050. 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());
  89051. };
  89052. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  89053. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  89054. var index = indices_1[_i];
  89055. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  89056. if (!node) {
  89057. throw new Error(context + ": Failed to find node " + index);
  89058. }
  89059. this._traverseNode(context, node, action, parentNode);
  89060. }
  89061. };
  89062. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  89063. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  89064. return;
  89065. }
  89066. if (!action(node, parentNode)) {
  89067. return;
  89068. }
  89069. if (node.children) {
  89070. this._traverseNodes(context, node.children, action, node);
  89071. }
  89072. };
  89073. GLTFLoader.prototype._loadAnimations = function () {
  89074. var animations = this._gltf.animations;
  89075. if (!animations) {
  89076. return;
  89077. }
  89078. for (var index = 0; index < animations.length; index++) {
  89079. var animation = animations[index];
  89080. this._loadAnimation("#/animations/" + index, animation);
  89081. }
  89082. };
  89083. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  89084. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  89085. for (var index = 0; index < animation.channels.length; index++) {
  89086. var channel = GLTFLoader._GetProperty(animation.channels, index);
  89087. if (!channel) {
  89088. throw new Error(context + ": Failed to find channel " + index);
  89089. }
  89090. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  89091. if (!sampler) {
  89092. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  89093. }
  89094. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  89095. }
  89096. };
  89097. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  89098. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  89099. if (!targetNode) {
  89100. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  89101. }
  89102. var targetPath;
  89103. var animationType;
  89104. switch (channel.target.path) {
  89105. case "translation": {
  89106. targetPath = "position";
  89107. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89108. break;
  89109. }
  89110. case "rotation": {
  89111. targetPath = "rotationQuaternion";
  89112. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  89113. break;
  89114. }
  89115. case "scale": {
  89116. targetPath = "scaling";
  89117. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89118. break;
  89119. }
  89120. case "weights": {
  89121. targetPath = "influence";
  89122. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  89123. break;
  89124. }
  89125. default: {
  89126. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  89127. }
  89128. }
  89129. var inputData;
  89130. var outputData;
  89131. var checkSuccess = function () {
  89132. if (!inputData || !outputData) {
  89133. return;
  89134. }
  89135. var outputBufferOffset = 0;
  89136. var getNextOutputValue;
  89137. switch (targetPath) {
  89138. case "position": {
  89139. getNextOutputValue = function () {
  89140. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  89141. outputBufferOffset += 3;
  89142. return value;
  89143. };
  89144. break;
  89145. }
  89146. case "rotationQuaternion": {
  89147. getNextOutputValue = function () {
  89148. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  89149. outputBufferOffset += 4;
  89150. return value;
  89151. };
  89152. break;
  89153. }
  89154. case "scaling": {
  89155. getNextOutputValue = function () {
  89156. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  89157. outputBufferOffset += 3;
  89158. return value;
  89159. };
  89160. break;
  89161. }
  89162. case "influence": {
  89163. getNextOutputValue = function () {
  89164. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  89165. var value = new Array(numTargets);
  89166. for (var i = 0; i < numTargets; i++) {
  89167. value[i] = outputData[outputBufferOffset++];
  89168. }
  89169. return value;
  89170. };
  89171. break;
  89172. }
  89173. }
  89174. sampler.interpolation = sampler.interpolation || "LINEAR";
  89175. var getNextKey;
  89176. switch (sampler.interpolation) {
  89177. case "STEP": {
  89178. getNextKey = function (frameIndex) { return ({
  89179. frame: inputData[frameIndex],
  89180. value: getNextOutputValue(),
  89181. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  89182. }); };
  89183. break;
  89184. }
  89185. case "LINEAR": {
  89186. getNextKey = function (frameIndex) { return ({
  89187. frame: inputData[frameIndex],
  89188. value: getNextOutputValue()
  89189. }); };
  89190. break;
  89191. }
  89192. case "CUBICSPLINE": {
  89193. getNextKey = function (frameIndex) { return ({
  89194. frame: inputData[frameIndex],
  89195. inTangent: getNextOutputValue(),
  89196. value: getNextOutputValue(),
  89197. outTangent: getNextOutputValue()
  89198. }); };
  89199. break;
  89200. }
  89201. default: {
  89202. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  89203. }
  89204. }
  89205. ;
  89206. var keys;
  89207. if (inputData.length === 1) {
  89208. var key = getNextKey(0);
  89209. keys = [
  89210. { frame: key.frame, value: key.value },
  89211. { frame: key.frame + 1, value: key.value }
  89212. ];
  89213. }
  89214. else {
  89215. keys = new Array(inputData.length);
  89216. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  89217. keys[frameIndex] = getNextKey(frameIndex);
  89218. }
  89219. }
  89220. if (targetPath === "influence") {
  89221. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  89222. var _loop_7 = function (targetIndex) {
  89223. var morphTarget = morphTargetManager.getTarget(targetIndex);
  89224. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  89225. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  89226. babylonAnimation.setKeys(keys.map(function (key) { return ({
  89227. frame: key.frame,
  89228. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  89229. value: key.value[targetIndex],
  89230. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  89231. }); }));
  89232. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  89233. };
  89234. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  89235. _loop_7(targetIndex);
  89236. }
  89237. }
  89238. else {
  89239. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  89240. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  89241. babylonAnimation.setKeys(keys);
  89242. if (targetNode.babylonAnimationTargets) {
  89243. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  89244. var target = _a[_i];
  89245. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  89246. }
  89247. }
  89248. }
  89249. };
  89250. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  89251. if (!inputAccessor) {
  89252. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  89253. }
  89254. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  89255. inputData = data;
  89256. checkSuccess();
  89257. });
  89258. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  89259. if (!outputAccessor) {
  89260. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  89261. }
  89262. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  89263. outputData = data;
  89264. checkSuccess();
  89265. });
  89266. };
  89267. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  89268. var _this = this;
  89269. this._addPendingData(buffer);
  89270. if (buffer.loadedData) {
  89271. onSuccess(buffer.loadedData);
  89272. this._removePendingData(buffer);
  89273. }
  89274. else if (buffer.loadedObservable) {
  89275. buffer.loadedObservable.add(function (buffer) {
  89276. onSuccess(buffer.loadedData);
  89277. _this._removePendingData(buffer);
  89278. });
  89279. }
  89280. else {
  89281. if (!buffer.uri) {
  89282. throw new Error(context + ": Uri is missing");
  89283. }
  89284. buffer.loadedObservable = new BABYLON.Observable();
  89285. buffer.loadedObservable.add(function (buffer) {
  89286. onSuccess(buffer.loadedData);
  89287. _this._removePendingData(buffer);
  89288. });
  89289. this._loadUriAsync(context, buffer.uri, function (data) {
  89290. buffer.loadedData = data;
  89291. buffer.loadedObservable.notifyObservers(buffer);
  89292. buffer.loadedObservable = undefined;
  89293. });
  89294. }
  89295. };
  89296. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  89297. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  89298. if (!buffer) {
  89299. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  89300. }
  89301. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  89302. var data;
  89303. try {
  89304. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  89305. }
  89306. catch (e) {
  89307. throw new Error(context + ": " + e.message);
  89308. }
  89309. onSuccess(data);
  89310. });
  89311. };
  89312. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  89313. var _this = this;
  89314. if (accessor.sparse) {
  89315. throw new Error(context + ": Sparse accessors are not currently supported");
  89316. }
  89317. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  89318. if (!bufferView) {
  89319. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  89320. }
  89321. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  89322. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  89323. var data;
  89324. var byteOffset = accessor.byteOffset || 0;
  89325. var byteStride = bufferView.byteStride;
  89326. if (byteStride === 0) {
  89327. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  89328. }
  89329. try {
  89330. switch (accessor.componentType) {
  89331. case GLTF2.EComponentType.BYTE: {
  89332. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89333. break;
  89334. }
  89335. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  89336. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89337. break;
  89338. }
  89339. case GLTF2.EComponentType.SHORT: {
  89340. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89341. break;
  89342. }
  89343. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  89344. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89345. break;
  89346. }
  89347. case GLTF2.EComponentType.UNSIGNED_INT: {
  89348. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89349. break;
  89350. }
  89351. case GLTF2.EComponentType.FLOAT: {
  89352. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  89353. break;
  89354. }
  89355. default: {
  89356. throw new Error(context + ": Invalid component type " + accessor.componentType);
  89357. }
  89358. }
  89359. }
  89360. catch (e) {
  89361. throw new Error(context + ": " + e);
  89362. }
  89363. onSuccess(data);
  89364. });
  89365. };
  89366. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  89367. byteOffset += data.byteOffset;
  89368. var targetLength = count * numComponents;
  89369. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  89370. return new typedArray(data.buffer, byteOffset, targetLength);
  89371. }
  89372. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  89373. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  89374. var targetBuffer = new typedArray(targetLength);
  89375. var sourceIndex = 0;
  89376. var targetIndex = 0;
  89377. while (targetIndex < targetLength) {
  89378. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  89379. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  89380. targetIndex++;
  89381. }
  89382. sourceIndex += elementStride;
  89383. }
  89384. return targetBuffer;
  89385. };
  89386. GLTFLoader.prototype._addPendingData = function (data) {
  89387. if (!this._renderReady) {
  89388. this._renderPendingCount++;
  89389. }
  89390. this._addLoaderPendingData(data);
  89391. };
  89392. GLTFLoader.prototype._removePendingData = function (data) {
  89393. var _this = this;
  89394. if (!this._renderReady) {
  89395. if (--this._renderPendingCount === 0) {
  89396. this._addLoaderPendingData(this);
  89397. this._compileMaterialsAsync(function () {
  89398. _this._compileShadowGeneratorsAsync(function () {
  89399. _this._removeLoaderPendingData(_this);
  89400. _this._renderReady = true;
  89401. _this._onRenderReady();
  89402. });
  89403. });
  89404. }
  89405. }
  89406. this._removeLoaderPendingData(data);
  89407. };
  89408. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  89409. this._loaderPendingCount++;
  89410. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  89411. var tracker = _a[_i];
  89412. tracker._addPendingData(data);
  89413. }
  89414. };
  89415. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  89416. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  89417. var tracker = _a[_i];
  89418. tracker._removePendingData(data);
  89419. }
  89420. if (--this._loaderPendingCount === 0) {
  89421. this._onComplete();
  89422. }
  89423. };
  89424. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  89425. var _this = this;
  89426. var tracker = new GLTFLoaderTracker(function () {
  89427. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  89428. onComplete();
  89429. });
  89430. this._loaderTrackers.push(tracker);
  89431. this._addLoaderPendingData(tracker);
  89432. action();
  89433. this._removeLoaderPendingData(tracker);
  89434. };
  89435. GLTFLoader.prototype._getDefaultMaterial = function () {
  89436. if (!this._defaultMaterial) {
  89437. var id = "__gltf_default";
  89438. var material = this._babylonScene.getMaterialByName(id);
  89439. if (!material) {
  89440. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  89441. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89442. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89443. material.metallic = 1;
  89444. material.roughness = 1;
  89445. }
  89446. this._defaultMaterial = material;
  89447. }
  89448. return this._defaultMaterial;
  89449. };
  89450. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  89451. var babylonMaterial = material.babylonMaterial;
  89452. // Ensure metallic workflow
  89453. babylonMaterial.metallic = 1;
  89454. babylonMaterial.roughness = 1;
  89455. var properties = material.pbrMetallicRoughness;
  89456. if (!properties) {
  89457. return;
  89458. }
  89459. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  89460. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  89461. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  89462. if (properties.baseColorTexture) {
  89463. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  89464. if (!texture) {
  89465. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  89466. }
  89467. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  89468. }
  89469. if (properties.metallicRoughnessTexture) {
  89470. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  89471. if (!texture) {
  89472. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  89473. }
  89474. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  89475. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  89476. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  89477. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  89478. }
  89479. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  89480. };
  89481. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  89482. if (material.babylonMaterial) {
  89483. assign(material.babylonMaterial, false);
  89484. return;
  89485. }
  89486. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  89487. return;
  89488. }
  89489. this._createPbrMaterial(material);
  89490. this._loadMaterialBaseProperties(context, material);
  89491. this._loadMaterialMetallicRoughnessProperties(context, material);
  89492. assign(material.babylonMaterial, true);
  89493. };
  89494. GLTFLoader.prototype._createPbrMaterial = function (material) {
  89495. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  89496. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89497. material.babylonMaterial = babylonMaterial;
  89498. };
  89499. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  89500. var babylonMaterial = material.babylonMaterial;
  89501. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  89502. if (material.doubleSided) {
  89503. babylonMaterial.backFaceCulling = false;
  89504. babylonMaterial.twoSidedLighting = true;
  89505. }
  89506. if (material.normalTexture) {
  89507. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  89508. if (!texture) {
  89509. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  89510. }
  89511. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  89512. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  89513. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  89514. if (material.normalTexture.scale != null) {
  89515. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  89516. }
  89517. }
  89518. if (material.occlusionTexture) {
  89519. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  89520. if (!texture) {
  89521. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  89522. }
  89523. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  89524. babylonMaterial.useAmbientInGrayScale = true;
  89525. if (material.occlusionTexture.strength != null) {
  89526. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  89527. }
  89528. }
  89529. if (material.emissiveTexture) {
  89530. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  89531. if (!texture) {
  89532. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  89533. }
  89534. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  89535. }
  89536. };
  89537. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  89538. var babylonMaterial = material.babylonMaterial;
  89539. var alphaMode = material.alphaMode || "OPAQUE";
  89540. switch (alphaMode) {
  89541. case "OPAQUE": {
  89542. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89543. break;
  89544. }
  89545. case "MASK": {
  89546. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  89547. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  89548. if (colorFactor) {
  89549. if (colorFactor[3] == 0) {
  89550. babylonMaterial.alphaCutOff = 1;
  89551. }
  89552. else {
  89553. babylonMaterial.alphaCutOff /= colorFactor[3];
  89554. }
  89555. }
  89556. if (babylonMaterial.albedoTexture) {
  89557. babylonMaterial.albedoTexture.hasAlpha = true;
  89558. }
  89559. break;
  89560. }
  89561. case "BLEND": {
  89562. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  89563. if (colorFactor) {
  89564. babylonMaterial.alpha = colorFactor[3];
  89565. }
  89566. if (babylonMaterial.albedoTexture) {
  89567. babylonMaterial.albedoTexture.hasAlpha = true;
  89568. babylonMaterial.useAlphaFromAlbedoTexture = true;
  89569. }
  89570. break;
  89571. }
  89572. default: {
  89573. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  89574. }
  89575. }
  89576. };
  89577. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  89578. var _this = this;
  89579. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  89580. if (!sampler) {
  89581. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  89582. }
  89583. this._loadSampler("#/samplers/" + sampler.index, sampler);
  89584. this._addPendingData(texture);
  89585. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  89586. _this._tryCatchOnError(function () {
  89587. _this._removePendingData(texture);
  89588. });
  89589. }, function (message) {
  89590. _this._tryCatchOnError(function () {
  89591. throw new Error(context + ": " + message);
  89592. });
  89593. });
  89594. if (texture.url) {
  89595. babylonTexture.updateURL(texture.url);
  89596. }
  89597. else if (texture.dataReadyObservable) {
  89598. texture.dataReadyObservable.add(function (texture) {
  89599. babylonTexture.updateURL(texture.url);
  89600. });
  89601. }
  89602. else {
  89603. texture.dataReadyObservable = new BABYLON.Observable();
  89604. texture.dataReadyObservable.add(function (texture) {
  89605. babylonTexture.updateURL(texture.url);
  89606. });
  89607. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  89608. if (!image_1) {
  89609. throw new Error(context + ": Failed to find source " + texture.source);
  89610. }
  89611. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  89612. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  89613. texture.dataReadyObservable.notifyObservers(texture);
  89614. texture.dataReadyObservable = undefined;
  89615. });
  89616. }
  89617. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  89618. babylonTexture.wrapU = sampler.wrapU;
  89619. babylonTexture.wrapV = sampler.wrapV;
  89620. babylonTexture.name = texture.name || "texture" + texture.index;
  89621. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  89622. return babylonTexture;
  89623. };
  89624. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  89625. if (sampler.noMipMaps != undefined) {
  89626. return;
  89627. }
  89628. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  89629. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  89630. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  89631. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  89632. };
  89633. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  89634. if (image.uri) {
  89635. this._loadUriAsync(context, image.uri, onSuccess);
  89636. }
  89637. else {
  89638. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  89639. if (!bufferView) {
  89640. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  89641. }
  89642. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  89643. }
  89644. };
  89645. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  89646. var _this = this;
  89647. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  89648. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  89649. return;
  89650. }
  89651. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  89652. throw new Error(context + ": Uri '" + uri + "' is invalid");
  89653. }
  89654. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  89655. _this._tryCatchOnError(function () {
  89656. onSuccess(new Uint8Array(data));
  89657. });
  89658. }, function (event) {
  89659. _this._tryCatchOnError(function () {
  89660. if (request && !_this._renderReady) {
  89661. request._lengthComputable = event.lengthComputable;
  89662. request._loaded = event.loaded;
  89663. request._total = event.total;
  89664. _this._onProgress();
  89665. }
  89666. });
  89667. }, this._babylonScene.database, true, function (request, exception) {
  89668. _this._tryCatchOnError(function () {
  89669. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  89670. });
  89671. });
  89672. this._requests.push(request);
  89673. };
  89674. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  89675. if (this._disposed) {
  89676. return;
  89677. }
  89678. try {
  89679. handler();
  89680. }
  89681. catch (e) {
  89682. BABYLON.Tools.Error("glTF Loader: " + e.message);
  89683. if (this._errorCallback) {
  89684. this._errorCallback(e.message, e);
  89685. }
  89686. this.dispose();
  89687. }
  89688. };
  89689. GLTFLoader._AssignIndices = function (array) {
  89690. if (array) {
  89691. for (var index = 0; index < array.length; index++) {
  89692. array[index].index = index;
  89693. }
  89694. }
  89695. };
  89696. GLTFLoader._GetProperty = function (array, index) {
  89697. if (!array || index == undefined || !array[index]) {
  89698. return null;
  89699. }
  89700. return array[index];
  89701. };
  89702. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  89703. // Set defaults if undefined
  89704. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  89705. switch (mode) {
  89706. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  89707. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  89708. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  89709. default:
  89710. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  89711. return BABYLON.Texture.WRAP_ADDRESSMODE;
  89712. }
  89713. };
  89714. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  89715. // Set defaults if undefined
  89716. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  89717. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  89718. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  89719. switch (minFilter) {
  89720. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  89721. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  89722. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  89723. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  89724. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  89725. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89726. default:
  89727. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89728. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89729. }
  89730. }
  89731. else {
  89732. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  89733. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  89734. }
  89735. switch (minFilter) {
  89736. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  89737. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  89738. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89739. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  89740. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  89741. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  89742. default:
  89743. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89744. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89745. }
  89746. }
  89747. };
  89748. GLTFLoader._GetNumComponents = function (context, type) {
  89749. switch (type) {
  89750. case "SCALAR": return 1;
  89751. case "VEC2": return 2;
  89752. case "VEC3": return 3;
  89753. case "VEC4": return 4;
  89754. case "MAT2": return 4;
  89755. case "MAT3": return 9;
  89756. case "MAT4": return 16;
  89757. }
  89758. throw new Error(context + ": Invalid type " + type);
  89759. };
  89760. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  89761. var _this = this;
  89762. if (this.useClipPlane) {
  89763. babylonMaterial.forceCompilation(babylonMesh, function () {
  89764. babylonMaterial.forceCompilation(babylonMesh, function () {
  89765. _this._tryCatchOnError(onSuccess);
  89766. }, { clipPlane: true });
  89767. });
  89768. }
  89769. else {
  89770. babylonMaterial.forceCompilation(babylonMesh, function () {
  89771. _this._tryCatchOnError(onSuccess);
  89772. });
  89773. }
  89774. };
  89775. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  89776. if (!this.compileMaterials || !this._gltf.materials) {
  89777. onSuccess();
  89778. return;
  89779. }
  89780. var meshes = this._getMeshes();
  89781. var remaining = 0;
  89782. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  89783. var mesh = meshes_1[_i];
  89784. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89785. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  89786. var subMaterial = _b[_a];
  89787. if (subMaterial) {
  89788. remaining++;
  89789. }
  89790. }
  89791. }
  89792. else if (mesh.material) {
  89793. remaining++;
  89794. }
  89795. }
  89796. if (remaining === 0) {
  89797. onSuccess();
  89798. return;
  89799. }
  89800. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  89801. var mesh = meshes_2[_c];
  89802. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89803. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  89804. var subMaterial = _e[_d];
  89805. if (subMaterial) {
  89806. this._compileMaterialAsync(subMaterial, mesh, function () {
  89807. if (--remaining === 0) {
  89808. onSuccess();
  89809. }
  89810. });
  89811. }
  89812. }
  89813. }
  89814. else if (mesh.material) {
  89815. this._compileMaterialAsync(mesh.material, mesh, function () {
  89816. if (--remaining === 0) {
  89817. onSuccess();
  89818. }
  89819. });
  89820. }
  89821. }
  89822. };
  89823. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  89824. var _this = this;
  89825. if (!this.compileShadowGenerators) {
  89826. onSuccess();
  89827. return;
  89828. }
  89829. var lights = this._babylonScene.lights;
  89830. var remaining = 0;
  89831. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  89832. var light = lights_1[_i];
  89833. var generator = light.getShadowGenerator();
  89834. if (generator) {
  89835. remaining++;
  89836. }
  89837. }
  89838. if (remaining === 0) {
  89839. onSuccess();
  89840. return;
  89841. }
  89842. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  89843. var light = lights_2[_a];
  89844. var generator = light.getShadowGenerator();
  89845. if (generator) {
  89846. generator.forceCompilation(function () {
  89847. if (--remaining === 0) {
  89848. _this._tryCatchOnError(onSuccess);
  89849. }
  89850. });
  89851. }
  89852. }
  89853. };
  89854. GLTFLoader.prototype._abortRequests = function () {
  89855. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  89856. var request = _a[_i];
  89857. request.abort();
  89858. }
  89859. this._requests.length = 0;
  89860. };
  89861. GLTFLoader.prototype._releaseResources = function () {
  89862. if (this._gltf.textures) {
  89863. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  89864. var texture = _a[_i];
  89865. if (texture.url) {
  89866. URL.revokeObjectURL(texture.url);
  89867. texture.url = undefined;
  89868. }
  89869. }
  89870. }
  89871. };
  89872. GLTFLoader.Extensions = {};
  89873. return GLTFLoader;
  89874. }());
  89875. GLTF2.GLTFLoader = GLTFLoader;
  89876. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  89877. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89878. })(BABYLON || (BABYLON = {}));
  89879. //# sourceMappingURL=babylon.glTFLoader.js.map
  89880. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89881. var BABYLON;
  89882. (function (BABYLON) {
  89883. var GLTF2;
  89884. (function (GLTF2) {
  89885. /**
  89886. * Utils functions for GLTF
  89887. */
  89888. var GLTFUtils = /** @class */ (function () {
  89889. function GLTFUtils() {
  89890. }
  89891. /**
  89892. * If the uri is a base64 string
  89893. * @param uri: the uri to test
  89894. */
  89895. GLTFUtils.IsBase64 = function (uri) {
  89896. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  89897. };
  89898. /**
  89899. * Decode the base64 uri
  89900. * @param uri: the uri to decode
  89901. */
  89902. GLTFUtils.DecodeBase64 = function (uri) {
  89903. var decodedString = atob(uri.split(",")[1]);
  89904. var bufferLength = decodedString.length;
  89905. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  89906. for (var i = 0; i < bufferLength; i++) {
  89907. bufferView[i] = decodedString.charCodeAt(i);
  89908. }
  89909. return bufferView.buffer;
  89910. };
  89911. GLTFUtils.ValidateUri = function (uri) {
  89912. return (uri.indexOf("..") === -1);
  89913. };
  89914. return GLTFUtils;
  89915. }());
  89916. GLTF2.GLTFUtils = GLTFUtils;
  89917. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89918. })(BABYLON || (BABYLON = {}));
  89919. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  89920. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89921. var BABYLON;
  89922. (function (BABYLON) {
  89923. var GLTF2;
  89924. (function (GLTF2) {
  89925. var GLTFLoaderExtension = /** @class */ (function () {
  89926. function GLTFLoaderExtension() {
  89927. this.enabled = true;
  89928. }
  89929. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  89930. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  89931. GLTFLoaderExtension.prototype._loadRoot = function (loader, context, root) { return false; };
  89932. GLTFLoaderExtension.prototype._loadScene = function (loader, context, scene) { return false; };
  89933. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  89934. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  89935. var _this = this;
  89936. if (!property.extensions) {
  89937. return false;
  89938. }
  89939. var extension = property.extensions[this.name];
  89940. if (!extension) {
  89941. return false;
  89942. }
  89943. // Clear out the extension before executing the action to avoid recursing into the same property.
  89944. property.extensions[this.name] = undefined;
  89945. action(context + "extensions/" + this.name, extension, function () {
  89946. // Restore the extension after completing the action.
  89947. property.extensions[_this.name] = extension;
  89948. });
  89949. return true;
  89950. };
  89951. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  89952. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  89953. };
  89954. GLTFLoaderExtension.LoadRoot = function (loader, context, root) {
  89955. return this._ApplyExtensions(function (extension) { return extension._loadRoot(loader, context, root); });
  89956. };
  89957. GLTFLoaderExtension.LoadScene = function (loader, context, scene) {
  89958. return this._ApplyExtensions(function (extension) { return extension._loadScene(loader, context, scene); });
  89959. };
  89960. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  89961. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  89962. };
  89963. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  89964. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  89965. };
  89966. GLTFLoaderExtension._ApplyExtensions = function (action) {
  89967. var extensions = GLTFLoaderExtension._Extensions;
  89968. if (!extensions) {
  89969. return false;
  89970. }
  89971. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  89972. var extension = extensions_1[_i];
  89973. if (extension.enabled && action(extension)) {
  89974. return true;
  89975. }
  89976. }
  89977. return false;
  89978. };
  89979. //
  89980. // Utilities
  89981. //
  89982. GLTFLoaderExtension._Extensions = [];
  89983. return GLTFLoaderExtension;
  89984. }());
  89985. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  89986. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89987. })(BABYLON || (BABYLON = {}));
  89988. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  89989. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89990. var BABYLON;
  89991. (function (BABYLON) {
  89992. var GLTF2;
  89993. (function (GLTF2) {
  89994. var Extensions;
  89995. (function (Extensions) {
  89996. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  89997. var MSFTLOD = /** @class */ (function (_super) {
  89998. __extends(MSFTLOD, _super);
  89999. function MSFTLOD() {
  90000. var _this = _super !== null && _super.apply(this, arguments) || this;
  90001. /**
  90002. * Specify the minimal delay between LODs in ms (default = 250)
  90003. */
  90004. _this.Delay = 250;
  90005. return _this;
  90006. }
  90007. Object.defineProperty(MSFTLOD.prototype, "name", {
  90008. get: function () {
  90009. return "MSFT_lod";
  90010. },
  90011. enumerable: true,
  90012. configurable: true
  90013. });
  90014. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  90015. return this._loadExtension(context, node, function (context, extension, onComplete) {
  90016. for (var i = extension.ids.length - 1; i >= 0; i--) {
  90017. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  90018. if (!lodNode) {
  90019. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  90020. }
  90021. loader._traverseNode(context, lodNode, action, parentNode);
  90022. }
  90023. loader._traverseNode(context, node, action, parentNode);
  90024. onComplete();
  90025. });
  90026. };
  90027. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  90028. var _this = this;
  90029. return this._loadExtension(context, node, function (context, extension, onComplete) {
  90030. var nodes = [node];
  90031. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  90032. var index = _a[_i];
  90033. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  90034. if (!lodNode) {
  90035. throw new Error(context + ": Failed to find node " + index);
  90036. }
  90037. nodes.push(lodNode);
  90038. }
  90039. loader._addLoaderPendingData(node);
  90040. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  90041. loader._removeLoaderPendingData(node);
  90042. onComplete();
  90043. });
  90044. });
  90045. };
  90046. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  90047. var _this = this;
  90048. loader._whenAction(function () {
  90049. loader._loadNode(context, nodes[index]);
  90050. }, function () {
  90051. if (index !== nodes.length - 1) {
  90052. var previousNode = nodes[index + 1];
  90053. previousNode.babylonMesh.setEnabled(false);
  90054. }
  90055. if (index === 0) {
  90056. onComplete();
  90057. return;
  90058. }
  90059. setTimeout(function () {
  90060. loader._tryCatchOnError(function () {
  90061. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  90062. });
  90063. }, _this.Delay);
  90064. });
  90065. };
  90066. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  90067. var _this = this;
  90068. return this._loadExtension(context, material, function (context, extension, onComplete) {
  90069. var materials = [material];
  90070. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  90071. var index = _a[_i];
  90072. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  90073. if (!lodMaterial) {
  90074. throw new Error(context + ": Failed to find material " + index);
  90075. }
  90076. materials.push(lodMaterial);
  90077. }
  90078. loader._addLoaderPendingData(material);
  90079. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  90080. loader._removeLoaderPendingData(material);
  90081. onComplete();
  90082. });
  90083. });
  90084. };
  90085. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  90086. var _this = this;
  90087. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  90088. if (index === materials.length - 1) {
  90089. assign(babylonMaterial, isNew);
  90090. // Load the next LOD when the loader is ready to render.
  90091. loader._executeWhenRenderReady(function () {
  90092. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  90093. });
  90094. }
  90095. else {
  90096. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  90097. assign(babylonMaterial, isNew);
  90098. if (index === 0) {
  90099. onComplete();
  90100. }
  90101. else {
  90102. setTimeout(function () {
  90103. loader._tryCatchOnError(function () {
  90104. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  90105. });
  90106. }, _this.Delay);
  90107. }
  90108. });
  90109. }
  90110. });
  90111. };
  90112. return MSFTLOD;
  90113. }(GLTF2.GLTFLoaderExtension));
  90114. Extensions.MSFTLOD = MSFTLOD;
  90115. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  90116. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  90117. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90118. })(BABYLON || (BABYLON = {}));
  90119. //# sourceMappingURL=MSFT_lod.js.map
  90120. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  90121. var BABYLON;
  90122. (function (BABYLON) {
  90123. var GLTF2;
  90124. (function (GLTF2) {
  90125. var Extensions;
  90126. (function (Extensions) {
  90127. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  90128. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  90129. function KHRMaterialsPbrSpecularGlossiness() {
  90130. return _super !== null && _super.apply(this, arguments) || this;
  90131. }
  90132. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  90133. get: function () {
  90134. return "KHR_materials_pbrSpecularGlossiness";
  90135. },
  90136. enumerable: true,
  90137. configurable: true
  90138. });
  90139. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  90140. var _this = this;
  90141. return this._loadExtension(context, material, function (context, extension, onComplete) {
  90142. loader._createPbrMaterial(material);
  90143. loader._loadMaterialBaseProperties(context, material);
  90144. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  90145. assign(material.babylonMaterial, true);
  90146. onComplete();
  90147. });
  90148. };
  90149. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  90150. var babylonMaterial = material.babylonMaterial;
  90151. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  90152. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  90153. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  90154. if (properties.diffuseTexture) {
  90155. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  90156. if (!texture) {
  90157. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  90158. }
  90159. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  90160. }
  90161. if (properties.specularGlossinessTexture) {
  90162. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  90163. if (!texture) {
  90164. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  90165. }
  90166. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  90167. babylonMaterial.reflectivityTexture.hasAlpha = true;
  90168. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  90169. }
  90170. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  90171. };
  90172. return KHRMaterialsPbrSpecularGlossiness;
  90173. }(GLTF2.GLTFLoaderExtension));
  90174. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  90175. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  90176. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  90177. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90178. })(BABYLON || (BABYLON = {}));
  90179. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  90180. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  90181. var BABYLON;
  90182. (function (BABYLON) {
  90183. var GLTF2;
  90184. (function (GLTF2) {
  90185. var Extensions;
  90186. (function (Extensions) {
  90187. var KHRLights = /** @class */ (function (_super) {
  90188. __extends(KHRLights, _super);
  90189. function KHRLights() {
  90190. return _super !== null && _super.apply(this, arguments) || this;
  90191. }
  90192. Object.defineProperty(KHRLights.prototype, "name", {
  90193. get: function () {
  90194. return "KHR_lights";
  90195. },
  90196. enumerable: true,
  90197. configurable: true
  90198. });
  90199. KHRLights.prototype.applyCommonProperties = function (light, lightInfo) {
  90200. if (lightInfo.color) {
  90201. light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
  90202. }
  90203. else {
  90204. light.diffuse.copyFromFloats(1, 1, 1);
  90205. }
  90206. if (lightInfo.intensity !== undefined) {
  90207. light.intensity = lightInfo.intensity;
  90208. }
  90209. else {
  90210. light.intensity = 1;
  90211. }
  90212. };
  90213. KHRLights.prototype._loadScene = function (loader, context, scene) {
  90214. return this._loadExtension(context, scene, function (context, extension, onComplete) {
  90215. if (extension.light >= 0 && loader._gltf.extensions) {
  90216. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  90217. if (lightInfo.type !== 'ambient') {
  90218. return;
  90219. }
  90220. var lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
  90221. loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
  90222. }
  90223. onComplete();
  90224. });
  90225. };
  90226. KHRLights.prototype._loadNode = function (loader, context, node) {
  90227. var _this = this;
  90228. return this._loadExtension(context, node, function (context, extension, onComplete) {
  90229. if (extension.light >= 0 && loader._gltf.extensions) {
  90230. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  90231. var name_1 = node.name || 'Light';
  90232. var matrix = void 0;
  90233. if (node.matrix) {
  90234. matrix = BABYLON.Matrix.FromArray(node.matrix);
  90235. }
  90236. else {
  90237. matrix = BABYLON.Matrix.Identity();
  90238. }
  90239. var direction = new BABYLON.Vector3(0, 0, 1);
  90240. if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
  90241. var rotationMatrix = matrix.getRotationMatrix();
  90242. BABYLON.Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
  90243. }
  90244. var light = void 0;
  90245. if (lightInfo.type == 'directional') {
  90246. light = new BABYLON.DirectionalLight(name_1, direction, loader._babylonScene);
  90247. }
  90248. else {
  90249. var position = matrix.getTranslation();
  90250. if (lightInfo.type == 'spot') {
  90251. var angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
  90252. light = new BABYLON.SpotLight(name_1, position, direction, angle, 2, loader._babylonScene);
  90253. }
  90254. else {
  90255. light = new BABYLON.PointLight(name_1, position, loader._babylonScene);
  90256. }
  90257. }
  90258. _this.applyCommonProperties(light, lightInfo);
  90259. extension.babylonLight = light;
  90260. extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
  90261. if (node.children) {
  90262. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  90263. var index = _a[_i];
  90264. var childNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  90265. if (!childNode) {
  90266. throw new Error(context + ": Failed to find child node " + index);
  90267. }
  90268. loader._loadNode("#/nodes/" + index, childNode);
  90269. }
  90270. }
  90271. }
  90272. onComplete();
  90273. });
  90274. };
  90275. KHRLights.prototype._loadRoot = function (loader, context, root) {
  90276. return this._loadExtension(context, root, function (context, extension, onComplete) {
  90277. extension.lights.forEach(function (light, idx) {
  90278. light.index = idx;
  90279. });
  90280. onComplete();
  90281. });
  90282. };
  90283. return KHRLights;
  90284. }(GLTF2.GLTFLoaderExtension));
  90285. Extensions.KHRLights = KHRLights;
  90286. GLTF2.GLTFLoader.RegisterExtension(new KHRLights());
  90287. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  90288. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90289. })(BABYLON || (BABYLON = {}));
  90290. //# sourceMappingURL=KHR_lights.js.map
  90291. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  90292. globalObject["BABYLON"] = BABYLON;
  90293. 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 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 HighlightLayer = BABYLON.HighlightLayer;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;
  90294. 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,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,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };